repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
ouyanghaiyong/Study_swift
DouYuZB/DouYuZBUITests/DouYuZBUITests.swift
1
1239
// // DouYuZBUITests.swift // DouYuZBUITests // // Created by ouyang on 2017/2/13. // Copyright © 2017年 ouyang. All rights reserved. // import XCTest class DouYuZBUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
mit
sheepy1/SelectionOfZhihu
SelectionOfZhihu/UserDetailModel.swift
1
1144
// // UserDetail.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/20. // Copyright © 2016年 Sheepy. All rights reserved. // import Foundation class UserDetailModel: NSObject { var ask = 0 as Int64 var answer = 0 as Int64 var post = 0 as Int64 var agree = 0 as Int64 var agreei = 0 as Int64 var agreeiratio = "" var agreeiw = 0 as Int64 var agreeiratiow = "" var ratio = 0 as Int64 var followee = 0 as Int64 var follower = 0 as Int64 var followeri = 0 as Int64 var followiratio = "" var followeriw = 0 as Int64 var followiratiow = "" var thanks = 0 as Int64 var tratio = 0 as Int64 var fav = 0 as Int64 var fratio = 0 as Int64 var logs = 0 as Int64 var mostvote = 0 as Int64 var mostvotepercent = "" var mostvote5 = 0 as Int64 var mostvote5percent = "" var mostvote10 = 0 as Int64 var mostvote10percent = "" var count10000 = 0 as Int64 var count5000 = 0 as Int64 var count2000 = 0 as Int64 var count1000 = 0 as Int64 var count500 = 0 as Int64 var count200 = 0 as Int64 var count100 = 0 as Int64 }
mit
k8mil/ContactCircularView
ContactCircularView/Classes/ContactCircularViewTextCreatorProtocol.swift
1
466
// // Created by Kamil Wysocki on 14/10/16. // Copyright (c) 2016 CocoaPods. All rights reserved. // import Foundation /** Protocol that you have to implement you want to create customTextFormatter and use it in ContactCircularView */ public protocol FormattedTextCreator { /** Implement this method to create formatted string in your class than responds to FormattedTextCreator protocol */ func formattedTextFromString(_ string: String) -> String }
mit
OpsLabJPL/MarsImagesIOS
Pods/SwiftMessages/SwiftMessages/MarginAdjustable+Animation.swift
4
2149
// // MarginAdjustable+Animation.swift // SwiftMessages // // Created by Timothy Moose on 11/5/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit extension MarginAdjustable where Self: UIView { public func defaultMarginAdjustment(context: AnimationContext) -> UIEdgeInsets { var layoutMargins: UIEdgeInsets = layoutMarginAdditions var safeAreaInsets: UIEdgeInsets if #available(iOS 11, *) { insetsLayoutMarginsFromSafeArea = false safeAreaInsets = self.safeAreaInsets } else { #if SWIFTMESSAGES_APP_EXTENSIONS let application: UIApplication? = nil #else let application: UIApplication? = UIApplication.shared #endif if !context.safeZoneConflicts.isDisjoint(with: [.statusBar]), let app = application, app.statusBarOrientation == .portrait || app.statusBarOrientation == .portraitUpsideDown { let frameInWindow = convert(bounds, to: window) let top = max(0, 20 - frameInWindow.minY) safeAreaInsets = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) } else { safeAreaInsets = .zero } } if !context.safeZoneConflicts.isDisjoint(with: .overStatusBar) { safeAreaInsets.top = 0 } layoutMargins = collapseLayoutMarginAdditions ? layoutMargins.collapse(toInsets: safeAreaInsets) : layoutMargins + safeAreaInsets return layoutMargins } } extension UIEdgeInsets { func collapse(toInsets insets: UIEdgeInsets) -> UIEdgeInsets { let top = self.top.collapse(toInset: insets.top) let left = self.left.collapse(toInset: insets.left) let bottom = self.bottom.collapse(toInset: insets.bottom) let right = self.right.collapse(toInset: insets.right) return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } } extension CGFloat { func collapse(toInset inset: CGFloat) -> CGFloat { return Swift.max(self, inset) } }
apache-2.0
apple/swift-tools-support-core
Tests/TSCUtilityTests/ProgressAnimationTests.swift
1
4010
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import XCTest import TSCUtility import TSCLibc import TSCTestSupport import TSCBasic typealias Thread = TSCBasic.Thread final class ProgressAnimationTests: XCTestCase { func testPercentProgressAnimationDumbTerminal() { var outStream = BufferedOutputByteStream() var animation = PercentProgressAnimation(stream: outStream, header: "TestHeader") runProgressAnimation(animation) XCTAssertEqual(outStream.bytes.validDescription, """ TestHeader 0%: 0 10%: 1 20%: 2 30%: 3 40%: 4 50%: 5 """) outStream = BufferedOutputByteStream() animation = PercentProgressAnimation(stream: outStream, header: "TestHeader") animation.complete(success: true) XCTAssertEqual(outStream.bytes.validDescription, "") } func testNinjaProgressAnimationDumbTerminal() { var outStream = BufferedOutputByteStream() var animation = NinjaProgressAnimation(stream: outStream) runProgressAnimation(animation) XCTAssertEqual(outStream.bytes.validDescription, """ [0/10] 0 [1/10] 1 [2/10] 2 [3/10] 3 [4/10] 4 [5/10] 5 """) outStream = BufferedOutputByteStream() animation = NinjaProgressAnimation(stream: outStream) animation.complete(success: true) XCTAssertEqual(outStream.bytes.validDescription, "") } #if !os(Windows) // PseudoTerminal is not supported in Windows func testPercentProgressAnimationTTY() throws { let output = try readingTTY { tty in let animation = PercentProgressAnimation(stream: tty.outStream, header: "TestHeader") runProgressAnimation(animation) } let startCyan = "\u{1B}[36m" let bold = "\u{1B}[1m" let end = "\u{1B}[0m" XCTAssertMatch(output.spm_chuzzle(), .prefix("\(startCyan)\(bold)TestHeader\(end)")) } func testNinjaProgressAnimationTTY() throws { var output = try readingTTY { tty in let animation = NinjaProgressAnimation(stream: tty.outStream) runProgressAnimation(animation) } let clearLine = "\u{1B}[2K\r" let newline = "\r\n" XCTAssertEqual(output, """ \(clearLine)[0/10] 0\ \(clearLine)[1/10] 1\ \(clearLine)[2/10] 2\ \(clearLine)[3/10] 3\ \(clearLine)[4/10] 4\ \(clearLine)[5/10] 5\(newline) """) output = try readingTTY { tty in let animation = NinjaProgressAnimation(stream: tty.outStream) animation.complete(success: true) } XCTAssertEqual(output, "") } private func readingTTY(_ closure: (PseudoTerminal) -> Void) throws -> String { guard let terminal = PseudoTerminal() else { struct PseudoTerminalCreationError: Error {} throw PseudoTerminalCreationError() } var output = "" let thread = Thread { while let out = terminal.readPrimary() { output += out } } thread.start() closure(terminal) terminal.closeSecondary() // Make sure to read the complete output before checking it. thread.join() terminal.closePrimary() return output } #endif private func runProgressAnimation(_ animation: ProgressAnimationProtocol) { for i in 0...5 { animation.update(step: i, total: 10, text: String(i)) } animation.complete(success: true) } }
apache-2.0
hrscy/TodayNews
News/News/Classes/Home/Model/NewsModel.swift
1
17332
// // NewsModel.swift // News // // Created by 杨蒙 on 2018/1/13. // Copyright © 2018年 hrscy. All rights reserved. // import HandyJSON /// 新闻数据模型(首页新闻数据,视频新闻数据,小视频,微头条) struct NewsModel: HandyJSON { var weitoutiaoHeight: CGFloat { // 50 + contentH + 5 + middleViewH + 65 var height: CGFloat = 120 height += contentH height += collectionViewH return height } /// collectionView 高度 var collectionViewH: CGFloat { return Calculate.collectionViewHeight(thumb_image_list.count) } /// collectionView 宽度 var collectionViewW: CGFloat { return Calculate.collectionViewWidth(thumb_image_list.count) } var imageCellHeight: CGFloat { // imageHeight + titleH! + 10 + 40 let imageHeight = screenWidth * 9.0 / 16.0 + titleH return imageHeight + 50 } var girlCellHeight: CGFloat { return contentH + 75 + screenWidth * 1.4 } var jokeCellHeight: CGFloat { // 15 + 50 + 10 + contentH! return 75 + contentH } var cellHeight: CGFloat { // 15 + titleH + 10 + middleViewH + 16 + 10 + bottomViewH + 10 var height: CGFloat = 61 + titleH if video_duration != 0 && video_style == 2 { height += screenWidth * 0.5 } if label_style == .ad && sub_title != "" { height += 40 } if middle_image.url != "" && image_list.count == 0 { return 95 } else { if image_list.count != 0 { if image_list.count == 1 { return 95 } else { height += image3Width } } } return height } var show_more: String = "" let emojiManager = EmojiManager() var ppmmCellHeight: CGFloat { return contentH + 75 + screenWidth * 1.4 } var content = "" var attributedContent: NSMutableAttributedString { return emojiManager.showEmoji(content: content, font: UIFont.systemFont(ofSize: 17)) } var contentH: CGFloat { return content.textHeight(fontSize: 16, width: screenWidth - 30) } var item_id: Int = 0 var cell_flag: Int = 0 var behot_time: Int = 0 var tip: Int = 0 var publish_time: TimeInterval = 0 var publishTime: String { return publish_time.convertString() } var create_time: TimeInterval = 0 var createTime: String { return create_time.convertString() } var source_icon_style: Int = 0 // 1,4,6 右侧视频 var tag_id: Int = 0 var media_info = MediaInfo() var user_info = NewsUserInfo() var user = NewsUserInfo() var preload_web: Int = 0 var cell_layout_style: Int = 0 var group_id: Int = 0 var cell_type: CellType = .none var log_pb = LogPB() var media_name: String = "" var user_repin: Int = 0 var display_url: String = "" var url: String = "" var repin_count: Int = 0 var repinCount: String { return read_count.convertString() } var stick_label: String = "" var show_portrait_article: Bool = false var action_list = [Action]() var user_digg = false var digg_count: Int = 0 var diggCount: String { return digg_count.convertString() } var has_m3u8_video: Bool = false var has_video: Bool = false var item_version: Int = 0 var share_count: Int = 0 var shareCount: String { return share_count.convertString() } var forward_count: Int = 0 var forwardCount: String { guard forward_count != 0 else { return "转发" } return forward_count.convertString() } var source: String = "" var article_alt_url: String = "" var comment_count: Int = 0 var commentCount: String { return comment_count.convertString() } var cursor: Int = 0 var video_style: Int = 0 var show_portrait: Bool = false var stick_style: Int = 0 var ignore_web_transform: Int = 0 var forward_info = ForwardInfo() var is_stick: Bool = false var verified_content: String = "" var share_url: String = "" var bury_count: Int = 0 var buryCount: String { return bury_count.convertString() } var article_sub_type: Int = 0 var allow_download: Bool = false var tag: String = "" var like_count: Int = 0 var likeCount: String { return like_count.convertString() } var level: Int = 0 var read_count: Int = 0 var readCount: String { return read_count.convertString() } var article_type: Int = 0 var user_verified = false var rid: String = "" var title: String = "" var titleH: CGFloat { if video_duration != 0 && video_style == 0 { // // 右侧有图 return title.textHeight(fontSize: 17, width: screenWidth * 0.72 - 30) } else { return title.textHeight(fontSize: 17, width: screenWidth - 30) } } var videoTitleH: CGFloat { return title.textHeight(fontSize: 16, width: screenWidth - 60) } var abstract: String = "" var is_subject: Bool = false var hot: Bool = false // 热 var keywords: String = "" var source_open_url: String = "" var article_url: String = "" var ban_comment: Int = 0 var ugc_recommend = UGCRecommend() var label: String = "" var aggr_type: Int = 0 var has_mp4_video: Int = 0 var hase_image = false var image_list = [ImageList]() var large_image_list = [LargeImage]() var thumb_image_list = [ThumbImage]() var middle_image = MiddleImage() var video_play_info = VideoPlayInfo() var video_detail_info = VideoDetailInfo() var raw_data = SmallVideo() //小视频数据 var video_duration: Int = 0 var video_id: String = "" var videoDuration: String { return video_duration.convertVideoDuration() } var gallary_flag = 0 var gallary_image_count = 0 var large_image = LargeImage() // 广告 var ad_button = ADButton() var ad_id = 0 var ad_label = "" var sub_title = "" var type = "" // app var label_style: NewsLabelStyle = .none // 3 是广告,1是置顶 var app_name = "" var appleid = "" var description = "" var descriptionH: CGFloat { return description.textHeight(fontSize: 13, width: screenWidth - 30) } var download_url = "" var card_type: CardType = .video var is_article = false var is_preview = false var web_url = "" /// 他们也在用 var user_cards = [UserCard]() var position = DongtaiPosition() var repost_params = RepostParam() // 来自。。。 var brand_info = "" } enum CellType: Int, HandyJSONEnum { case none = 0 /// 用户 case user = 32 /// 相关关注 case relatedConcern = 50 } enum NewsLabelStyle: Int, HandyJSONEnum { case none = 0 case topOrLive = 1 // 置顶或直播 case ad = 3 // 广告 } /// 视频类型 enum CardType: String, HandyJSONEnum { case video = "video" // 视频 case adVideo = "ad_video" // 广告视频 case adTextlink = "ad_textlink" // 广告链接 } struct ADButton: HandyJSON { var description: String = "" var download_url: String = "" var id: Int = 0 var web_url: String = "" var app_name: String = "" var track_url: String = "" var ui_type: Int = 0 var click_track_url: String = "" var button_text: String = "" var display_type: Int = 0 var hide_if_exists: Int = 0 var open_url: String = "" var source: String = "" var type: String = "" var package: String = "" var appleid: String = "" var web_title: String = "" } struct SmallVideo: HandyJSON { let emojiManager = EmojiManager() var rich_title: String = "" var group_id: Int = 0 var status = Status() var thumb_image_list = [ThumbImage]() var title: String = "" var attrbutedText: NSMutableAttributedString { return emojiManager.showEmoji(content: title, font: UIFont.systemFont(ofSize: 17)) } var create_time: TimeInterval = 0 var createTime: String { return create_time.convertString() } var recommand_reason: String = "" var first_frame_image_list = [FirstFrameImage]() var action = SmallVideoAction() var app_download = AppDownload() var app_schema: String = "" var interact_label: String = "" var activity: String = "" var large_image_list = [LargeImage]() var group_source: GroupSource = .huoshan var share = Share() var publish_reason = PublishReason() var music = Music() var title_rich_span: String = "" var user = User() var video = Video() var label: String = "" var label_for_list: String = "" var distance: String = "" var detail_schema: String = "" var item_id: Int = 0 var animated_image_list = [AnimatedImage]() var video_neardup_id: Int = 0 /// 他们也在用 var user_cards = [UserCard]() var has_more = false var id = 0 var show_more = "" var show_more_jump_url = "" } /// 小视频类型 enum GroupSource: Int, HandyJSONEnum { case huoshan = 16 case douyin = 19 } struct SmallVideoAction: HandyJSON { var bury_count = 0 var buryCount: String { return bury_count.convertString() } var comment_count = 0 var commentCount: String { return comment_count.convertString() } var digg_count = 0 var diggCount: String { return digg_count.convertString() } var forward_count = 0 var forwardCount: String { return forward_count.convertString() } var play_count = 0 var playCount: String { return play_count.convertString() } var read_count = 0 var readCount: String { return read_count.convertString() } var user_bury = 0 var userBury: String { return user_bury.convertString() } var user_repin = 0 var userRepin: String { return user_repin.convertString() } var user_digg = false } struct AnimatedImage: HandyJSON { var uri: String = "" var image_type: Int = 0 var url_list = [URLList]() var url: String = "" var width: Int = 0 var height: Int = 0 } struct OriginCover: HandyJSON { var uri: String = "" var url_list = [String]() } struct PlayAddr: HandyJSON { var uri: String = "" var url_list = [String]() } struct DownloadAddr: HandyJSON { var uri: String = "" var url_list = [String]() } struct User: HandyJSON { var relation_count = RelationCount() var relation = Relation() var info = Info() } struct Info: HandyJSON { var medals: String = "" var avatar_url: String = "" var schema: String = "" var user_auth_info = UserAuthInfo() var user_id: Int = 0 var desc: String = "" var ban_status: Bool = false var user_verified = false var verified_content: String = "" var media_id: String = "" var name: String = "" var user_decoration: String = "" } struct Relation: HandyJSON { var is_followed = false var is_friend = false var is_following = false var remark_name: String = "" } struct RelationCount: HandyJSON { var followings_count: Int = 0 var followingsCount: String { return followings_count.convertString() } var followers_count: Int = 0 var followersCount: String { return followers_count.convertString() } } struct Music: HandyJSON { var author: String = "" var music_id: Int = 0 var title: String = "" var cover_large: String = "" var album: String = "" var cover_medium: String = "" var cover_thumb: String = "" var cover_hd: String = "" } struct PublishReason: HandyJSON { var noun: String = "" var verb: String = "" } struct AppDownload: HandyJSON { var flag: Int = 0 var text: String = "" } struct Share: HandyJSON { var share_title: String = "" var share_url: String = "" var share_weibo_desc: String = "" var share_cover: String = "" var share_desc: String = "" } struct FirstFrameImage: HandyJSON { var uri: String = "" var image_type: Int = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: Int = 0 var height: Int = 0 } struct Status: HandyJSON { var allow_share: Bool = false var allow_download: Bool = false var allow_comment: Bool = false var is_delete: Bool = false } struct VideoDetailInfo: HandyJSON { var video_preloading_flag: Int = 0 var direct_play: Int = 0 var group_flags: Int = 0 var video_url = [VideoURL]() var detail_video_large_image = DetailVideoLargeImage() var video_third_monitor_url: String = "" var video_watching_count: Int = 0 var videoWatchingCount: String { return video_watching_count.convertString() } var video_id: String = "" var video_watch_count: Int = 0 var videoWatchCount: String { return video_watch_count.convertString() } var video_type: Int = 0 var show_pgc_subscribe: Int = 0 } struct DetailVideoLargeImage: HandyJSON { var height: Int = 0 var url_list: [URLList]! var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: Int = 0 var uri: String = "" } struct VideoURL: HandyJSON { } struct MiddleImage: HandyJSON { var type = ImageType.normal var height: CGFloat = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: CGFloat = 0 var uri: String = "" /// 宽高比 var ratio: CGFloat? { return width / height } } /// 图片的类型 enum ImageType: Int, HandyJSONEnum { case normal = 1 // 一般图片 case gif = 2 // gif 图 } struct ImageList: HandyJSON { var type = ImageType.normal var height: CGFloat = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: CGFloat = 0 var uri: String = "" /// 宽高比 var ratio: CGFloat? { return width / height } } struct NewsUserInfo: HandyJSON { var follow: Bool = false var name: String = "" var user_verified: Bool = false var verified_content: String = "" var user_id: Int = 0 var id: Int = 0 var description: String = "" var desc: String = "" var avatar_url: String = "" var follower_count: Int = 0 var followerCount: String { return follower_count.convertString() } var user_decoration: String! var subcribed: Int = 0 var fans_count: Int = 0 var fansCount: String { return fans_count.convertString() } var special_column = [SpecialColumn]() var user_auth_info: String! var media_id: Int = 0 var screen_name = "" var is_followed: Bool = false var is_following: Bool = false // 是否正在关注 var is_blocking: Bool = false var is_blocked: Bool = false var is_friend: Bool = false var medals = [String]() // hot_post (热门内容) } struct ForwardInfo: HandyJSON { var forward_count: Int = 0 var forwardCount: String { return forward_count.convertString() } } struct UGCRecommend: HandyJSON { var activity = "" var reason = "" } struct MediaInfo: HandyJSON { var follow: Bool = false var is_star_user: Bool = false var recommend_reason: String = "" var user_verified: Bool = false var media_id: Int = 0 var verified_content: String = "" var user_id: Int = 0 var recommend_type: Int = 0 var avatar_url: String = "" var name: String = "" } struct LogPB: HandyJSON { var impr_id: String = "" } struct Extra: HandyJSON { } struct Action: HandyJSON { var extra = Extra() var action: Int = 0 var desc: String = "" } struct FilterWord: HandyJSON { var id: String = "" var name: String = "" var is_selected: Bool = false } struct DnsInfo: HandyJSON { } struct OriginalPlayURL: HandyJSON { var main_url: String = "" var backup_url: String = "" } struct VideoPlayInfo: HandyJSON { var status: Int = 0 var dns_info = DnsInfo() var enable_ssl: Bool = false var poster_url: String = "" var message: String = "" var video_list = VideoList() var original_play_url = OriginalPlayURL() var video_duration: Int = 0 var videoDuration: String { return video_duration.convertVideoDuration() } var validate: String = "" } struct NewsDetailImage: HandyJSON { var url: String = "" var width: CGFloat = 0 var height: CGFloat = 0 var rate: CGFloat = 1 var url_list = [URLList]() }
mit
ubiregiinc/UbiregiExtensionClient
UbiregiExtensionClientTests/TestHelper.swift
1
2018
import Foundation import Swifter import XCTest func withSwifter(port: UInt16 = 8081, k: (HttpServer) throws -> ()) { let server = HttpServer() try! server.start(port) defer { server.stop() } try! k(server) } func returnJSON(object: [String: AnyObject]) -> HttpRequest -> HttpResponse { return { (response: HttpRequest) in HttpResponse.OK(HttpResponseBody.Json(object)) } } func dictionary(pairs: [(String, String)]) -> [String: String] { var h: [String: String] = [:] for p in pairs { h[p.0] = p.1 } return h } class NotificationTrace: NSObject { var notifications: [NSNotification] override init() { self.notifications = [] } func didReceiveNotification(notification: NSNotification) { self.notifications.append(notification) } func notificationNames() -> [String] { return self.notifications.map { $0.name } } func observeNotification(name: String, object: AnyObject?) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNotification:", name: name, object: object) } } func waitFor(timeout: NSTimeInterval, message: String? = nil, predicate: () -> Bool) { let endTime = NSDate().dateByAddingTimeInterval(timeout) while NSDate().compare(endTime) == NSComparisonResult.OrderedAscending { NSThread.sleepForTimeInterval(0.1) if predicate() { return } } XCTAssert(false, message ?? "Timeout exceeded for waitFor") } func globally(timeout: NSTimeInterval = 1, message: String? = nil, predicate: () -> Bool) { let endTime = NSDate().dateByAddingTimeInterval(timeout) while NSDate().compare(endTime) == NSComparisonResult.OrderedAscending { NSThread.sleepForTimeInterval(0.1) if !predicate() { XCTAssert(false, message ?? "predicate does not hold which expected to hold globally") return } } }
mit
SwiftGen/SwiftGen
Sources/TestUtils/Fixtures/Generated/Colors/swift5/multiple.swift
2
4076
// swiftlint:disable all // Generated using SwiftGen — https://github.com/SwiftGen/SwiftGen #if os(macOS) import AppKit.NSColor internal typealias Color = NSColor #elseif os(iOS) || os(tvOS) || os(watchOS) import UIKit.UIColor internal typealias Color = UIColor #endif // swiftlint:disable superfluous_disable_command file_length implicit_return // MARK: - Colors // swiftlint:disable identifier_name line_length type_body_length internal struct ColorName { internal let rgbaValue: UInt32 internal var color: Color { return Color(named: self) } internal enum Colors { /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#339666"></span> /// Alpha: 100% <br/> (0x339666ff) internal static let articleBody = ColorName(rgbaValue: 0x339666ff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span> /// Alpha: 100% <br/> (0xff66ccff) internal static let articleFootnote = ColorName(rgbaValue: 0xff66ccff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#33fe66"></span> /// Alpha: 100% <br/> (0x33fe66ff) internal static let articleTitle = ColorName(rgbaValue: 0x33fe66ff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span> /// Alpha: 80% <br/> (0xffffffcc) internal static let `private` = ColorName(rgbaValue: 0xffffffcc) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span> /// Alpha: 100% <br/> (0xff66ccff) internal static let themeCyan = ColorName(rgbaValue: 0xff66ccff) } internal enum Extra { /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#339666"></span> /// Alpha: 100% <br/> (0x339666ff) internal static let articleBody = ColorName(rgbaValue: 0x339666ff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span> /// Alpha: 100% <br/> (0xff66ccff) internal static let articleFootnote = ColorName(rgbaValue: 0xff66ccff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#33fe66"></span> /// Alpha: 100% <br/> (0x33fe66ff) internal static let articleTitle = ColorName(rgbaValue: 0x33fe66ff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ff66cc"></span> /// Alpha: 100% <br/> (0xff66ccff) internal static let cyanColor = ColorName(rgbaValue: 0xff66ccff) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span> /// Alpha: 80% <br/> (0xffffffcc) internal static let namedValue = ColorName(rgbaValue: 0xffffffcc) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span> /// Alpha: 80% <br/> (0xffffffcc) internal static let nestedNamedValue = ColorName(rgbaValue: 0xffffffcc) /// <span style="display:block;width:3em;height:2em;border:1px solid black;background:#ffffff"></span> /// Alpha: 80% <br/> (0xffffffcc) internal static let `private` = ColorName(rgbaValue: 0xffffffcc) } } // swiftlint:enable identifier_name line_length type_body_length // MARK: - Implementation Details internal extension Color { convenience init(rgbaValue: UInt32) { let components = RGBAComponents(rgbaValue: rgbaValue).normalized self.init(red: components[0], green: components[1], blue: components[2], alpha: components[3]) } } private struct RGBAComponents { let rgbaValue: UInt32 private var shifts: [UInt32] { [ rgbaValue >> 24, // red rgbaValue >> 16, // green rgbaValue >> 8, // blue rgbaValue // alpha ] } private var components: [CGFloat] { shifts.map { CGFloat($0 & 0xff) } } var normalized: [CGFloat] { components.map { $0 / 255.0 } } } internal extension Color { convenience init(named color: ColorName) { self.init(rgbaValue: color.rgbaValue) } }
mit
ayo1103/Test-Youtube-ios-player-helper
TestYoutubeIosPlayerHelper/TestYoutubeIosPlayerHelperTests/TestYoutubeIosPlayerHelperTests.swift
1
951
// // TestYoutubeIosPlayerHelperTests.swift // TestYoutubeIosPlayerHelperTests // // Created by Bryan Lin on 6/23/15. // Copyright (c) 2015 ayo1103. All rights reserved. // import UIKit import XCTest class TestYoutubeIosPlayerHelperTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
sschiau/swift
test/Syntax/syntax_diagnostics.swift
1
151
// RUN: %target-swift-frontend -emit-syntax -primary-file %s -verify typealias Inner: Foo // expected-error{{expected '=' in type alias declaration}}
apache-2.0
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/Controllers/FormViewController.swift
1
1715
// // FomerViewController.swift // Former-Demo // // Created by Ryo Aoyama on 7/23/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public class FormViewController: UIViewController { // MARK: Public public let tableView: UITableView = { let tableView = UITableView(frame: CGRect.zero, style: .Grouped) tableView.backgroundColor = .clearColor() tableView.contentInset.bottom = 10 tableView.sectionHeaderHeight = 0 tableView.sectionFooterHeight = 0 tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.01)) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.01)) tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() public lazy var former: Former = Former(tableView: self.tableView) public override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: Private private final func setup() { view.backgroundColor = .groupTableViewBackgroundColor() view.insertSubview(tableView, atIndex: 0) let tableConstraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[table]-0-|", options: [], metrics: nil, views: ["table": tableView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[table]-0-|", options: [], metrics: nil, views: ["table": tableView] ) ].flatMap { $0 } view.addConstraints(tableConstraints) } }
mit
zapdroid/RXWeather
Pods/RxCocoa/RxCocoa/Traits/SharedSequence/Variable+SharedSequence.swift
1
632
// // Variable+SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 12/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif extension Variable { /// Converts `Variable` to `SharedSequence` unit. /// /// - returns: Observable sequence. public func asSharedSequence<SharingStrategy: SharingStrategyProtocol>(strategy _: SharingStrategy.Type = SharingStrategy.self) -> SharedSequence<SharingStrategy, E> { let source = asObservable() .observeOn(SharingStrategy.scheduler) return SharedSequence(source) } }
mit
Acidburn0zzz/firefox-ios
SyncTests/MockSyncServerTests.swift
11
9156
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Account import Storage @testable import Sync import UIKit import XCTest class MockSyncServerTests: XCTestCase { var server: MockSyncServer! var client: Sync15StorageClient! override func setUp() { server = MockSyncServer(username: "1234567") server.start() client = getClient(server: server) } private func getClient(server: MockSyncServer) -> Sync15StorageClient? { guard let url = server.baseURL.asURL else { XCTFail("Couldn't get URL.") return nil } let authorizer: Authorizer = identity let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass) return Sync15StorageClient(serverURI: url, authorizer: authorizer, workQueue: queue, resultQueue: queue, backoff: MockBackoffStorage()) } func testDeleteSpec() { // Deletion of a collection path itself, versus trailing slash, sets the right flags. let all = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: [:])! XCTAssertTrue(all.wholeCollection) XCTAssertNil(all.ids) let some = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks", withQuery: ["ids": "123456,abcdef" as AnyObject])! XCTAssertFalse(some.wholeCollection) XCTAssertEqual(["123456", "abcdef"], some.ids!) let one = SyncDeleteRequestSpec.fromPath(path: "/1.5/123456/storage/bookmarks/123456", withQuery: [:])! XCTAssertFalse(one.wholeCollection) XCTAssertNil(one.ids) } func testInfoCollections() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords(records: [], inCollection: "tabs", now: 1326252222500) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: Bytes.generateGUID(), modified: 0)], inCollection: "clients", now: 1326253333000) let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.getInfoCollections().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents. XCTAssertEqual(response.value.collectionNames().sorted(), ["bookmarks", "clients", "tabs"]) XCTAssertEqual(response.value.modified("bookmarks"), 1326252222000) XCTAssertEqual(response.value.modified("clients"), 1326253333000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertEqual(response.metadata.records, 3) // bookmarks, clients, tabs. // X-Last-Modified, max of all collection modified timestamps. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326253333000) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testGet() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "guid", modified: 0)], inCollection: "bookmarks", now: 1326251111000) let collectionClient = client.clientForCollection("bookmarks", encrypter: getEncrypter()) let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! collectionClient.get("guid").upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents. XCTAssertEqual(response.value.id, "guid") XCTAssertEqual(response.value.modified, 1326251111000) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertEqual(response.metadata.lastModifiedMilliseconds, 1326251111000) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) // And now a missing record, which should produce a 404. collectionClient.get("missing").upon { result in XCTAssertNotNil(result.failureValue) guard let response = result.failureValue else { expectation.fulfill() return } XCTAssertNotNil(response as? NotFound<HTTPURLResponse>) } } func testWipeStorage() { server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "a", modified: 0)], inCollection: "bookmarks", now: 1326251111000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "b", modified: 0)], inCollection: "bookmarks", now: 1326252222000) server.storeRecords(records: [MockSyncServer.makeValidEnvelope(guid: "c", modified: 0)], inCollection: "clients", now: 1326253333000) server.storeRecords(records: [], inCollection: "tabs") // For now, only testing wiping the storage root, which is the only thing we use in practice. let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.wipeStorage().upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // JSON contents: should be the empty object. let jsonData = try! response.value.rawData() let jsonString = String(data: jsonData, encoding: .utf8)! XCTAssertEqual(jsonString, "{}") // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really wiped the data. XCTAssertTrue(self.server.collections.isEmpty) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testPut() { // For now, only test uploading crypto/keys. There's nothing special about this PUT, however. let expectation = self.expectation(description: "Waiting for result.") let before = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! client.uploadCryptoKeys(Keys.random(), withSyncKeyBundle: KeyBundle.random(), ifUnmodifiedSince: nil).upon { result in XCTAssertNotNil(result.successValue) guard let response = result.successValue else { expectation.fulfill() return } let after = decimalSecondsStringToTimestamp(millisecondsToDecimalSeconds(Date.now()))! // Contents: should be just the record timestamp. XCTAssertLessThanOrEqual(before, response.value) XCTAssertLessThanOrEqual(response.value, after) // X-Weave-Timestamp. XCTAssertLessThanOrEqual(before, response.metadata.timestampMilliseconds) XCTAssertLessThanOrEqual(response.metadata.timestampMilliseconds, after) // X-Weave-Records. XCTAssertNil(response.metadata.records) // X-Last-Modified. XCTAssertNil(response.metadata.lastModifiedMilliseconds) // And we really uploaded the record. XCTAssertNotNil(self.server.collections["crypto"]) XCTAssertNotNil(self.server.collections["crypto"]?.records["keys"]) expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } }
mpl-2.0
mluisbrown/Memories
Core/Sources/Utilities/UIButton.swift
1
657
import UIKit extension UIButton { public static func circlePlayButton(diameter: CGFloat) -> UIButton { let button = UIButton(type: .custom) button.frame = CGRect(origin: .zero, size: CGSize(width: diameter, height: diameter)) let circleImageNormal = CAShapeLayer.circlePlayShape(fillColor: .white, diameter: diameter).toImage() button.setImage(circleImageNormal, for: .normal) let circleImageHighlighted = CAShapeLayer.circlePlayShape(fillColor: .lightGray, diameter: diameter).toImage() button.setImage(circleImageHighlighted, for: .highlighted) return button } }
mit
practicalswift/swift
benchmark/single-source/ArraySetElement.swift
2
1244
//===--- ArraySetElement.swift ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils // 33% isUniquelyReferenced // 15% swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native // 18% swift_isUniquelyReferencedOrPinned_nonNull_native public var ArraySetElement = BenchmarkInfo( name: "ArraySetElement", runFunction: run_ArraySetElement, tags: [.runtime, .cpubench] ) // This is an effort to defeat isUniquelyReferenced optimization. Ideally // microbenchmarks list this should be written in C. @inline(never) func storeArrayElement(_ array: inout [Int], _ i: Int) { array[i] = i } public func run_ArraySetElement(_ N: Int) { var array = [Int](repeating: 0, count: 10000) for _ in 0..<10*N { for i in 0..<array.count { storeArrayElement(&array, i) } } }
apache-2.0
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Models/Base/BaseModel.swift
1
364
// // BaseModel.swift // Rocket.Chat // // Created by Rafael K. Streit on 7/8/16. // Copyright © 2016 Rocket.Chat. All rights reserved. // import Foundation import RealmSwift import SwiftyJSON public class BaseModel: Object { dynamic var identifier: String? public override static func primaryKey() -> String? { return "identifier" } }
mit
priyanka16/RPChatUI
RPChatUI/Classes/TimeSlotTableViewCell.swift
1
3881
// // TimeSlotTableViewCell.swift // // // Created by Priyanka // Copyright © 2017 __MyCompanyName__. All rights reserved. // import UIKit let timeTabletWidth: CGFloat = 150 let timeTabletHeight: CGFloat = 50 fileprivate let itemsPerRow: CGFloat = 3 protocol TimeSlotTableViewCellDelegate : class { func didSelectTime() } class TimeSlotTableViewCell: ChatMessageCell { var timeOptions = NSDictionary() fileprivate let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 9.0, right: 10.0) weak var delegate: TimeSlotTableViewCellDelegate? @IBOutlet weak var daysTableView: UITableView! @IBOutlet weak var timeslotTableView: UITableView! @IBOutlet weak var containerViewTopConstraint: NSLayoutConstraint! func setupCell(message: ChatMessage) { let viewYconstant = super.computedTextAreaHeight(message: message) super.setupWithMessage(message: message) self.messageBubbleView.frame.origin.x = (self.botImageView.bounds.width + 10) containerViewTopConstraint.constant = viewYconstant + 10 if let dict = message.options?[0] { if let timeDict = dict["availableTimeSlots"] as? NSDictionary { timeOptions = timeDict } } } func remainingDaysOfWeek() -> Int { let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = myCalendar.components(.weekday, from: Date()) let weekDay = myComponents.weekday! - 1 return 7 - weekDay } func dayOfWeek(day: Date) -> Int { let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = calendar.components(.weekday, from: day) return myComponents.weekday! } func dayOfWeek(dayIndex: Int) -> String { let weekDay = Calendar.current.date(byAdding: .day, value: dayIndex, to: Date()) let dateFormatter = DateFormatter() let daysOfWeek = dateFormatter.shortWeekdaySymbols let dayIndex = dayOfWeek(day: weekDay!)-1 return (daysOfWeek?[dayIndex])! } func dayOfWeekKeyString(dayIndex: Int) -> String { let weekDay = Calendar.current.date(byAdding: .day, value: dayIndex, to: Date()) let dateFormatter = DateFormatter() let daysOfWeek = dateFormatter.weekdaySymbols let dayIndex = dayOfWeek(day: weekDay!)-1 return (daysOfWeek?[dayIndex])! } } extension TimeSlotTableViewCell: UITableViewDataSource { private func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return remainingDaysOfWeek() } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (tableView == daysTableView) { let cell = tableView.dequeueReusableCell(withIdentifier: "DayNameTableViewCell", for: indexPath) cell.textLabel?.font = UIFont(name: "SFUIText-Regular", size: 16.0) cell.textLabel?.textColor = UIColor(red: 49 / 255.0, green: 63 / 255.0, blue: 72 / 255.0, alpha: 1.0) cell.textLabel?.text = dayOfWeek(dayIndex: indexPath.row) cell.textLabel?.textAlignment = .right return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "TimeSlotTubeTableViewCell", for: indexPath) as! TimeSlotTubeTableViewCell let weekdayKey = dayOfWeekKeyString(dayIndex: indexPath.row).lowercased() if let timeSlots = timeOptions.object(forKey: weekdayKey) as? [String] { cell.setupCell(timeDate: timeSlots) } return cell } } }
mit
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/SDK/Models/Error.swift
2
2783
import Foundation public class _VKError : ErrorType, CustomStringConvertible { public var domain : String public var code: Int public var desc : String public var userInfo : [NSObject: AnyObject]? ///The reference to a request to the API, in which the error occurred public var request : Request? public var description : String { return "VK.Error \(domain)_(\(code)): \(desc)" } public init(ns: NSError, req: Request?) { self.domain = ns.domain self.code = ns.code self.desc = ns.localizedDescription self.userInfo = ns.userInfo self.request = req if let request = request { VK.Log.put(request, "Init error of error and request \(self)") } } public init(domain: String, code: Int, desc: String, userInfo: [NSObject: AnyObject]?, req: Request?) { self.domain = domain self.code = code self.desc = desc self.userInfo = userInfo self.request = req if let request = request { VK.Log.put(request, "Init custom error \(self)") } } public init(json : JSON, request : Request) { self.request = request domain = "APIError" code = json["error_code"].intValue desc = json["error_msg"].stringValue var info = [NSObject : AnyObject]() for param in json["request_params"].arrayValue { info[param["key"].stringValue] = param["value"].stringValue } for (key, value) in json.dictionaryValue { if key != "request_params" && key != "error_code" { info[key] = value.stringValue } } userInfo = info VK.Log.put(request, "Init error of JSON \(self)") } public func `catch`() { if let request = request { VK.Log.put(request, "Catch error \(self)") } switch self.domain { case "APIError": catchAPIDomain() default: finaly() } } private func catchAPIDomain() { switch code { case 5: request?.authFails += 1 request?.attempts -= 1 Authorizator.autorize(request) case 6, 9, 10: Connection.needLimit = true finaly() case 14: if !sharedCaptchaIsRun { request?.attempts -= 1 СaptchaController.start( sid: userInfo!["captcha_sid"] as! String, imageUrl: userInfo!["captcha_img"] as! String, request: request!) } case 17: request?.attempts -= 1 WebController.validate(request!, validationUrl: userInfo!["redirect_uri"] as! String) default: finaly() } } public func finaly() { if let request = request { request.trySend() } } deinit { if let request = request { request.isAPI ? VK.Log.put(request, "DEINIT \(self)") : () } } }
apache-2.0
jpsachse/mensa-griebnitzsee
Mensa Griebnitzsee/ViewController.swift
1
6479
// // ViewController.swift // Mensa Griebnitzsee // // Copyright © 2017 Jan Philipp Sachse. All rights reserved. // import UIKit import MensaKit class ViewController: UICollectionViewController { let menuLoader = MenuLoader() var loadedMenu: Menu? let dateFormatter = DateFormatter() let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() dateFormatter.locale = NSLocale.current dateFormatter.dateStyle = .full dateFormatter.timeStyle = .none refreshControl.addTarget(self, action: #selector(updateMenu), for: .valueChanged) collectionView?.addSubview(refreshControl) // support dragging of entries into other apps, because why not collectionView?.dragDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.layoutIfNeeded() updateCollectionViewLayout() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { [unowned self] (context) in self.updateCollectionViewLayout() }) { (context) in } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshControl.beginRefreshing() let order = Calendar.current.compare(menuLoader.lastUpdatedDate, to: Date(), toGranularity: .day) if order == .orderedSame, let menu = menuLoader.loadMenuFromDisk() { self.loadedMenu = menu self.collectionView?.reloadData() self.refreshControl.endRefreshing() } else { updateMenu() } } @objc func updateMenu() { menuLoader.load { [unowned self] (menu) in self.loadedMenu = menu DispatchQueue.main.async { [unowned self] in self.collectionView?.reloadData() self.refreshControl.endRefreshing() } } } func updateCollectionViewLayout() { if UIApplication.shared.keyWindow?.traitCollection.horizontalSizeClass == .regular { collectionView?.collectionViewLayout = getColumnLayout() } else { collectionView?.collectionViewLayout = getRowLayout() } } func getCommonLayout(with padding: CGFloat) -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 10 layout.sectionInset = UIEdgeInsetsMake(padding, padding, padding, padding) layout.headerReferenceSize = CGSize(width: collectionView!.frame.width, height: 40) return layout } func getRowLayout() -> UICollectionViewFlowLayout { let defaultPadding: CGFloat = 10 let rowLayout = getCommonLayout(with: defaultPadding) rowLayout.itemSize = CGSize(width: collectionView!.frame.width - 2 * defaultPadding, height: 100) return rowLayout } func getColumnLayout() -> UICollectionViewFlowLayout { let defaultPadding: CGFloat = 10 let rowLayout = getCommonLayout(with: defaultPadding) rowLayout.itemSize = CGSize(width: collectionView!.frame.width / 2 - 1.5 * defaultPadding, height: 150) return rowLayout } override func numberOfSections(in collectionView: UICollectionView) -> Int { if let loadedMenu = loadedMenu { return loadedMenu.entries.count } return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let loadedMenu = loadedMenu { let entry = loadedMenu.entries[section] if entry.closed { return 1 } return loadedMenu.entries[section].dishes.count } return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let loadedMenu = loadedMenu, indexPath.section < loadedMenu.entries.count else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "noDataCell", for: indexPath) cell.layer.cornerRadius = 10 return cell } let entry = loadedMenu.entries[indexPath.section] var cell: UICollectionViewCell! if entry.closed { cell = collectionView.dequeueReusableCell(withReuseIdentifier: "closedCell", for: indexPath) } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: "menuCell", for: indexPath) if let cell = cell as? MenuCollectionViewCell, indexPath.row < entry.dishes.count { let dish = entry.dishes[indexPath.row] cell.categoryLabel.text = dish.category cell.dishNameLabel.text = dish.name cell.notesLabel.text = dish.notes.joined(separator: ", ") } } cell.layer.cornerRadius = 10 return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) guard let menuHeader = view as? MenuHeaderCollectionReusableView else { return view } if let loadedMenu = loadedMenu { let dateString = dateFormatter.string(from: loadedMenu.entries[indexPath.section].date) menuHeader.label.text = dateString } else { menuHeader.label.text = nil } return view } } extension ViewController: UICollectionViewDragDelegate { func getDragItems(for indexPath: IndexPath) -> [UIDragItem] { guard let loadedMenu = loadedMenu, indexPath.section < loadedMenu.entries.count, indexPath.row < loadedMenu.entries[indexPath.section].dishes.count else { return [] } let dish = loadedMenu.entries[indexPath.section].dishes[indexPath.row] let provider = NSItemProvider(object: dish.description as NSString) let item = UIDragItem(itemProvider: provider) return [item] } func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { return getDragItems(for: indexPath) } func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { return getDragItems(for: indexPath) } }
mit
adamnemecek/AudioKit
Sources/AudioKit/Internals/Hardware/Device.swift
1
2809
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if os(macOS) /// DeviceID isan AudioDeviceID on macOS public typealias DeviceID = AudioDeviceID #else /// DeviceID is a string on iOS public typealias DeviceID = String #endif import AVFoundation /// Wrapper for audio device selection public struct Device: Equatable, Hashable { /// The human-readable name for the device. public private(set) var name: String /// Number of input channels public private(set) var inputChannelCount: Int? /// Number of output channels public private(set) var outputChannelCount: Int? /// The device identifier. public private(set) var deviceID: DeviceID /// Initialize the device /// /// - Parameters: /// - name: The human-readable name for the device. /// - deviceID: The device identifier. /// - dataSource: String describing data source /// public init(name: String, deviceID: DeviceID, dataSource: String = "") { self.name = name self.deviceID = deviceID #if !os(macOS) if dataSource != "" { self.deviceID = "\(deviceID) \(dataSource)" } #endif } #if os(macOS) /// Initialize the device /// - Parameter deviceID: DeviceID public init(deviceID: DeviceID) { self.init(name: AudioDeviceUtils.name(deviceID), deviceID: deviceID) inputChannelCount = AudioDeviceUtils.inputChannels(deviceID) outputChannelCount = AudioDeviceUtils.outputChannels(deviceID) } #endif #if !os(macOS) /// Initialize the device /// /// - Parameters: /// - portDescription: A port description object that describes a single /// input or output port associated with an audio route. /// public init(portDescription: AVAudioSessionPortDescription) { let portData = [portDescription.uid, portDescription.selectedDataSource?.dataSourceName] let deviceID = portData.compactMap { $0 }.joined(separator: " ") self.init(name: portDescription.portName, deviceID: deviceID) } /// Return a port description matching the devices name. var portDescription: AVAudioSessionPortDescription? { return AVAudioSession.sharedInstance().availableInputs?.filter { $0.portName == name }.first } /// Return a data source matching the devices deviceID. var dataSource: AVAudioSessionDataSourceDescription? { let dataSources = portDescription?.dataSources ?? [] return dataSources.filter { deviceID.contains($0.dataSourceName) }.first } #endif } extension Device: CustomDebugStringConvertible { /// Printout for debug public var debugDescription: String { return "<Device: \(name) (\(deviceID))>" } }
mit
nathantannar4/Parse-Dashboard-for-iOS-Pro
Parse Dashboard for iOS/Models/DeepLink.swift
1
3092
// // DeepLink.swift // Parse Dashboard for iOS // // Copyright © 2017 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 12/15/17. // import UIKit enum DeepLink { case add, recent, support, home var type: String { switch self { case .add: return "me.nathantannar.Parse-Dashboard.add" case .recent: return "me.nathantannar.Parse-Dashboard.recent" case .support: return "me.nathantannar.Parse-Dashboard.support" case .home: return "me.nathantannar.Parse-Dashboard.home" } } var icon: UIApplicationShortcutIcon { switch self { case .add: return UIApplicationShortcutIcon(type: .add) case .recent: return UIApplicationShortcutIcon(type: .time) case .support: return UIApplicationShortcutIcon(type: .love) case .home: return UIApplicationShortcutIcon(type: .home) } } var item: UIMutableApplicationShortcutItem { switch self { case .add: return UIMutableApplicationShortcutItem(type: type, localizedTitle: Localizable.add.localized, localizedSubtitle: "New Configuration", icon: icon, userInfo: nil) case .recent: let config = UserDefaults.standard.value(forKey: .recentConfig) as? [String:String] return UIMutableApplicationShortcutItem(type: type, localizedTitle: Localizable.recent.localized, localizedSubtitle: config?[.configName], icon: icon, userInfo: config) case .support: return UIMutableApplicationShortcutItem(type: type, localizedTitle: Localizable.support.localized, localizedSubtitle: Localizable.makeDonation.localized, icon: icon, userInfo: nil) case .home: return UIMutableApplicationShortcutItem(type: type, localizedTitle: Localizable.home.localized, localizedSubtitle: "Saved Configurations", icon: icon, userInfo: nil) } } }
mit
spark/photon-tinker-ios
Photon-Tinker/Global/Extensions/ParticleDevice.swift
1
6166
// // Created by Raimundas Sakalauskas on 2019-05-09. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation extension ParticleDevice { func isRunningTinker() -> Bool { if (self.connected && self.functions.contains("digitalread") && self.functions.contains("digitalwrite") && self.functions.contains("analogwrite") && self.functions.contains("analogread")) { return true } else { return false } } func is3rdGen() -> Bool { return self.type == .argon || self.type == .boron || self.type == .xenon || self.type == .aSeries || self.type == .bSeries || self.type == .xSeries || self.type == .b5SoM } func getName() -> String { if let name = self.name, name.count > 0 { return name } else { return TinkerStrings.Device.NoName } } func getInfoDetails() -> [String: Any] { var info: [String: Any] = [:] info[TinkerStrings.InfoSlider.DeviceCell.DeviceType] = self.type info[TinkerStrings.InfoSlider.DeviceCell.DeviceId] = self.id ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.Serial] = self.serialNumber ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.DeviceOS] = self.systemFirmwareVersion ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.LastIPAddress] = self.lastIPAdress ?? TinkerStrings.InfoSlider.DeviceCell.Unknown if let lastHeard = self.lastHeard { info[TinkerStrings.InfoSlider.DeviceCell.LastHeard] = DateFormatter.localizedString(from: lastHeard, dateStyle: .medium, timeStyle: .short) } else { info[TinkerStrings.InfoSlider.DeviceCell.LastHeard] = TinkerStrings.InfoSlider.DeviceCell.Never } if (self.cellular) { info[TinkerStrings.InfoSlider.DeviceCell.IMEI] = self.imei ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.LastICCID] = self.lastIccid ?? TinkerStrings.InfoSlider.DeviceCell.Unknown } return info } func getInfoDetailsOrder() -> [String] { if (self.cellular) { return [TinkerStrings.InfoSlider.DeviceCell.DeviceType, TinkerStrings.InfoSlider.DeviceCell.DeviceId, TinkerStrings.InfoSlider.DeviceCell.Serial, TinkerStrings.InfoSlider.DeviceCell.IMEI, TinkerStrings.InfoSlider.DeviceCell.LastICCID, TinkerStrings.InfoSlider.DeviceCell.DeviceOS, TinkerStrings.InfoSlider.DeviceCell.LastIPAddress, TinkerStrings.InfoSlider.DeviceCell.LastHeard] } else { return [TinkerStrings.InfoSlider.DeviceCell.DeviceType, TinkerStrings.InfoSlider.DeviceCell.DeviceId, TinkerStrings.InfoSlider.DeviceCell.Serial, TinkerStrings.InfoSlider.DeviceCell.DeviceOS, TinkerStrings.InfoSlider.DeviceCell.LastIPAddress, TinkerStrings.InfoSlider.DeviceCell.LastHeard] } } } extension ParticleDeviceType { func getImage() -> UIImage? { switch (self) { case .core: return UIImage(named: "ImgDeviceCore") case .electron: return UIImage(named: "ImgDeviceElectron") case .photon: return UIImage(named: "ImgDevicePhoton") case .P1: return UIImage(named: "ImgDeviceP1") case .raspberryPi: return UIImage(named: "ImgDeviceRaspberryPi") case .redBearDuo: return UIImage(named: "ImgDeviceRedBearDuo") case .bluz: return UIImage(named: "ImgDeviceBluz") case .digistumpOak: return UIImage(named: "ImgDeviceDigistumpOak") case .xenon: return UIImage(named: "ImgDeviceXenon") case .argon: return UIImage(named: "ImgDeviceArgon") case .boron: return UIImage(named: "ImgDeviceBoron") case .xSeries: return UIImage(named: "ImgDeviceXenon") case .aSeries: return UIImage(named: "ImgDeviceArgon") case .bSeries: return UIImage(named: "ImgDeviceBoron") case .b5SoM: return UIImage(named: "ImgDeviceBoron") default: return UIImage(named: "ImgDeviceUnknown") } } func getIconColor() -> UIColor { switch (self) { case .core: return UIColor(rgb: 0x76777A) case .electron: return UIColor(rgb: 0x00AE42) case .photon, .P1: return UIColor(rgb: 0xB31983) case .raspberryPi, .redBearDuo, .ESP32, .bluz: return UIColor(rgb: 0x76777A) case .argon, .aSeries: return UIColor(rgb: 0x00AEEF) case .boron, .bSeries, .b5SoM: return UIColor(rgb: 0xED1C24) case .xenon, .xSeries: return UIColor(rgb: 0xF5A800) default: return UIColor(rgb: 0x76777A) } } func getIconText() -> String { switch (self) { case .core: return "C" case .electron: return "E" case .photon: return "P" case .P1: return "1" case .raspberryPi: return "R" case .redBearDuo: return "D" case .ESP32: return "ES" case .bluz: return "BZ" case .xenon, .xSeries: return "X" case .argon, .aSeries: return "A" case .boron, .bSeries, .b5SoM: return "B" default: return "?" } } }
apache-2.0
ObjectAlchemist/OOUIKit
Sources/Screen/ScreenOR.swift
1
1717
// // ScreenOR.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit import OOBase /** A screen container that displays primary OR secondary child content depending on condition. The container listens for changes in the adapter and updates content automatically. */ public final class ScreenOR: OOScreen { // MARK: init public init(condition: OOBool, conditionChangeListener: OOEventInform, isTrue primary: @escaping (UIViewController) -> OOScreen, isFalse secondary: @escaping (UIViewController) -> OOScreen) { self.condition = condition self.conditionChangeListener = conditionChangeListener self.primary = primary self.secondary = secondary } // MARK: protocol OOScreen public var ui: UIViewController { let controller = ORContainerViewController(primaryAvailable: condition, primary: primary, secondary: secondary) conditionChangeListener.set(onEvent: { [weak controller] in controller?.update() }) return controller } // MARK: private private let condition: OOBool private let conditionChangeListener: OOEventInform private let primary: (UIViewController) -> OOScreen private let secondary: (UIViewController) -> OOScreen } // convenience initializer public extension ScreenOR { convenience init(condition: OOWritableBool & OOEventInform, isTrue primary: @escaping (UIViewController) -> OOScreen, isFalse secondary: @escaping (UIViewController) -> OOScreen) { self.init(condition: condition, conditionChangeListener: condition, isTrue: primary, isFalse: secondary) } }
mit
sekouperry/bemyeyes-ios
BeMyEyes/Source/Other sources/KeychainAccess/Keychain.swift
2
136516
// // Keychain.swift // KeychainAccess // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import Security public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" public enum ItemClass { case GenericPassword case InternetPassword } public enum ProtocolType { case FTP case FTPAccount case HTTP case IRC case NNTP case POP3 case SMTP case SOCKS case IMAP case LDAP case AppleTalk case AFP case Telnet case SSH case FTPS case HTTPS case HTTPProxy case HTTPSProxy case FTPProxy case SMB case RTSP case RTSPProxy case DAAP case EPPC case IPP case NNTPS case LDAPS case TelnetS case IMAPS case IRCS case POP3S } public enum AuthenticationType { case NTLM case MSN case DPA case RPA case HTTPBasic case HTTPDigest case HTMLForm case Default } public enum Accessibility { case WhenUnlocked case AfterFirstUnlock case Always case WhenPasscodeSetThisDeviceOnly case WhenUnlockedThisDeviceOnly case AfterFirstUnlockThisDeviceOnly case AlwaysThisDeviceOnly } public enum AuthenticationPolicy : Int { case UserPresence } public enum FailableOf<T> { case Success(Value<T?>) case Failure(NSError) init(_ value: T?) { self = .Success(Value(value)) } init(_ error: NSError) { self = .Failure(error) } public var succeeded: Bool { switch self { case .Success: return true default: return false } } public var failed: Bool { switch self { case .Failure: return true default: return false } } public var error: NSError? { switch self { case .Failure(let error): return error default: return nil } } public var value: T? { switch self { case .Success(let success): return success.value default: return nil } } } public class Value<T> { let value: T init(_ value: T) { self.value = value } } public class Keychain { public var itemClass: ItemClass { return options.itemClass } public var service: String { return options.service } public var accessGroup: String? { return options.accessGroup } public var server: NSURL { return options.server } public var protocolType: ProtocolType { return options.protocolType } public var authenticationType: AuthenticationType { return options.authenticationType } public var accessibility: Accessibility { return options.accessibility } @availability(iOS, introduced=8.0) @availability(OSX, introduced=10.10) public var authenticationPolicy: AuthenticationPolicy? { return options.authenticationPolicy } public var synchronizable: Bool { return options.synchronizable } public var label: String? { return options.label } public var comment: String? { return options.comment } @availability(iOS, introduced=8.0) @availability(OSX, unavailable) public var authenticationPrompt: String? { return options.authenticationPrompt } private let options: Options private let NSFoundationVersionNumber_iOS_7_1 = 1047.25 private let NSFoundationVersionNumber_iOS_8_0 = 1140.11 private let NSFoundationVersionNumber_iOS_8_1 = 1141.1 private let NSFoundationVersionNumber10_9_2 = 1056.13 // MARK: public convenience init() { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } self.init(options) } public convenience init(service: String) { var options = Options() options.service = service self.init(options) } public convenience init(accessGroup: String) { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } options.accessGroup = accessGroup self.init(options) } public convenience init(service: String, accessGroup: String) { var options = Options() options.service = service options.accessGroup = accessGroup self.init(options) } public convenience init(server: String, protocolType: ProtocolType) { self.init(server: NSURL(string: server)!, protocolType: protocolType) } public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType) { self.init(server: NSURL(string: server)!, protocolType: protocolType, authenticationType: .Default) } public convenience init(server: NSURL, protocolType: ProtocolType) { self.init(server: server, protocolType: protocolType, authenticationType: .Default) } public convenience init(server: NSURL, protocolType: ProtocolType, authenticationType: AuthenticationType) { var options = Options() options.itemClass = .InternetPassword options.server = server options.protocolType = protocolType options.authenticationType = authenticationType self.init(options) } private init(_ opts: Options) { options = opts } // MARK: public func accessibility(accessibility: Accessibility) -> Keychain { var options = self.options options.accessibility = accessibility return Keychain(options) } @availability(iOS, introduced=8.0) @availability(OSX, introduced=10.10) public func accessibility(accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain { var options = self.options options.accessibility = accessibility options.authenticationPolicy = authenticationPolicy return Keychain(options) } public func synchronizable(synchronizable: Bool) -> Keychain { var options = self.options options.synchronizable = synchronizable return Keychain(options) } public func label(label: String) -> Keychain { var options = self.options options.label = label return Keychain(options) } public func comment(comment: String) -> Keychain { var options = self.options options.comment = comment return Keychain(options) } @availability(iOS, introduced=8.0) @availability(OSX, unavailable) public func authenticationPrompt(authenticationPrompt: String) -> Keychain { var options = self.options options.authenticationPrompt = authenticationPrompt return Keychain(options) } // MARK: public func get(key: String) -> String? { return getString(key) } public func getString(key: String) -> String? { let failable = getStringOrError(key) return failable.value } public func getData(key: String) -> NSData? { let failable = getDataOrError(key) return failable.value } public func getStringOrError(key: String) -> FailableOf<String> { let failable = getDataOrError(key) switch failable { case .Success: if let data = failable.value { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { return FailableOf(string) } return FailableOf(conversionError(message: "failed to convert data to string")) } else { return FailableOf(nil) } case .Failure(let error): return FailableOf(error) } } public func getDataOrError(key: String) -> FailableOf<NSData> { var query = options.query() query[kSecMatchLimit as! String] = kSecMatchLimitOne query[kSecReturnData as! String] = kCFBooleanTrue query[kSecAttrAccount as! String] = key var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let data = result as? NSData { return FailableOf(data) } return FailableOf(securityError(status: Status.UnexpectedError.rawValue)) case errSecItemNotFound: return FailableOf(nil) default: () } return FailableOf(securityError(status: status)) } // MARK: public func set(value: String, key: String) -> NSError? { if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { return set(data, key: key) } return conversionError(message: "failed to convert string to data") } public func set(value: NSData, key: String) -> NSError? { var query = options.query() query[kSecAttrAccount as! String] = key #if os(iOS) if floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) { query[kSecUseNoAuthenticationUI as! String] = kCFBooleanTrue } #endif var status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess, errSecInteractionNotAllowed: var query = options.query() query[kSecAttrAccount as! String] = key var (attributes, error) = options.attributes(key: nil, value: value) if var error = error { println("error:[\(error.code)] \(error.localizedDescription)") return error } else { if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { var error = remove(key) if error != nil { return error } else { return set(value, key: key) } } else { status = SecItemUpdate(query, attributes) } if status != errSecSuccess { return securityError(status: status) } } case errSecItemNotFound: var (attributes, error) = options.attributes(key: key, value: value) if var error = error { println("error:[\(error.code)] \(error.localizedDescription)") return error } else { status = SecItemAdd(attributes, nil) if status != errSecSuccess { return securityError(status: status) } } default: return securityError(status: status) } return nil } // MARK: public func remove(key: String) -> NSError? { var query = options.query() query[kSecAttrAccount as! String] = key let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { return securityError(status: status) } return nil } public func removeAll() -> NSError? { var query = options.query() #if !os(iOS) query[kSecMatchLimit as! String] = kSecMatchLimitAll #endif let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { return securityError(status: status) } return nil } // MARK: public func contains(key: String) -> Bool { var query = options.query() query[kSecAttrAccount as! String] = key var status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess: return true case errSecItemNotFound: return false default: securityError(status: status) return false } } // MARK: public subscript(key: String) -> String? { get { return get(key) } set { if let value = newValue { set(value, key: key) } else { remove(key) } } } // MARK: public class func allKeys(itemClass: ItemClass) -> [(String, String)] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items).map { switch itemClass { case .GenericPassword: return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String) case .InternetPassword: return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String) } } } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allKeys() -> [String] { return self.dynamicType.prettify(itemClass: itemClass, items: items()).map { $0["key"] as! String } } public class func allItems(itemClass: ItemClass) -> [[String: AnyObject]] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue #if os(iOS) query[kSecReturnData as! String] = kCFBooleanTrue #endif var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items) } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allItems() -> [[String: AnyObject]] { return self.dynamicType.prettify(itemClass: itemClass, items: items()) } #if os(iOS) @availability(iOS, introduced=8.0) public func getSharedPassword(completion: (account: String?, password: String?, error: NSError?) -> () = { account, password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in if let credential = credentials.first { let account = credential["account"] let password = credential["password"] completion(account: account, password: password, error: error) } else { completion(account: nil, password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(account: nil, password: nil, error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func getSharedPassword(account: String, completion: (password: String?, error: NSError?) -> () = { password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in if let credential = credentials.first { if let password = credential["password"] { completion(password: password, error: error) } else { completion(password: nil, error: error) } } else { completion(password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(password: nil, error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func setSharedPassword(password: String, account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(password as String?, account: account, completion: completion) } #endif #if os(iOS) private func setSharedPassword(password: String?, account: String, completion: (error: NSError?) -> () = { e -> () in }) { if let domain = server.host { SecAddSharedWebCredential(domain, account, password) { error -> () in if let error = error { completion(error: error.error) } else { completion(error: nil) } } } else { let error = securityError(status: Status.Param.rawValue) completion(error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func removeSharedPassword(account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(nil, account: account, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: nil, account: nil, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(#domain: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain, account: nil, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(#domain: String, account: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain as String?, account: account as String?, completion: completion) } #endif #if os(iOS) private class func requestSharedWebCredential(#domain: String?, account: String?, completion: (credentials: [[String: String]], error: NSError?) -> ()) { SecRequestSharedWebCredential(domain, account) { (credentials, error) -> () in var remoteError: NSError? if let error = error { remoteError = error.error if remoteError?.code != Int(errSecItemNotFound) { println("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)") } } if let credentials = credentials as? [[String: AnyObject]] { let credentials = credentials.map { credentials -> [String: String] in var credential = [String: String]() if let server = credentials[kSecAttrServer as! String] as? String { credential["server"] = server } if let account = credentials[kSecAttrAccount as! String] as? String { credential["account"] = account } if let password = credentials[kSecSharedPassword.takeUnretainedValue() as! String] as? String { credential["password"] = password } return credential } completion(credentials: credentials, error: remoteError) } else { completion(credentials: [], error: remoteError) } } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func generatePassword() -> String { return SecCreateSharedWebCredentialPassword().takeUnretainedValue() as! String } #endif // MARK: private func items() -> [[String: AnyObject]] { var query = options.query() query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue #if os(iOS) query[kSecReturnData as! String] = kCFBooleanTrue #endif var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return items } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } private class func prettify(#itemClass: ItemClass, items: [[String: AnyObject]]) -> [[String: AnyObject]] { let items = items.map { attributes -> [String: AnyObject] in var item = [String: AnyObject]() item["class"] = itemClass.description switch itemClass { case .GenericPassword: if let service = attributes[kSecAttrService as! String] as? String { item["service"] = service } if let accessGroup = attributes[kSecAttrAccessGroup as! String] as? String { item["accessGroup"] = accessGroup } case .InternetPassword: if let server = attributes[kSecAttrServer as! String] as? String { item["server"] = server } if let proto = attributes[kSecAttrProtocol as! String] as? String { if let protocolType = ProtocolType(rawValue: proto) { item["protocol"] = protocolType.description } } if let auth = attributes[kSecAttrAuthenticationType as! String] as? String { if let authenticationType = AuthenticationType(rawValue: auth) { item["authenticationType"] = authenticationType.description } } } if let key = attributes[kSecAttrAccount as! String] as? String { item["key"] = key } if let data = attributes[kSecValueData as! String] as? NSData { if let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { item["value"] = text } else { item["value"] = data } } if let accessible = attributes[kSecAttrAccessible as! String] as? String { if let accessibility = Accessibility(rawValue: accessible) { item["accessibility"] = accessibility.description } } if let synchronizable = attributes[kSecAttrSynchronizable as! String] as? Bool { item["synchronizable"] = synchronizable ? "true" : "false" } return item } return items } // MARK: private class func conversionError(#message: String) -> NSError { let error = NSError(domain: KeychainAccessErrorDomain, code: Int(Status.ConversionError.rawValue), userInfo: [NSLocalizedDescriptionKey: message]) println("error:[\(error.code)] \(error.localizedDescription)") return error } private func conversionError(#message: String) -> NSError { return self.dynamicType.conversionError(message: message) } private class func securityError(#status: OSStatus) -> NSError { let message = Status(rawValue: status)!.description let error = NSError(domain: KeychainAccessErrorDomain, code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) println("OSStatus error:[\(error.code)] \(error.localizedDescription)") return error } private func securityError(#status: OSStatus) -> NSError { return self.dynamicType.securityError(status: status) } } struct Options { var itemClass: ItemClass = .GenericPassword var service: String = "" var accessGroup: String? = nil var server: NSURL! var protocolType: ProtocolType! var authenticationType: AuthenticationType = .Default var accessibility: Accessibility = .AfterFirstUnlock var authenticationPolicy: AuthenticationPolicy? var synchronizable: Bool = false var label: String? var comment: String? var authenticationPrompt: String? init() {} } extension Keychain : Printable, DebugPrintable { public var description: String { let items = allItems() if items.isEmpty { return "[]" } var description = "[\n" for item in items { description += " " description += "\(item)\n" } description += "]" return description } public var debugDescription: String { return "\(items())" } } extension Options { func query() -> [String: AnyObject] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecAttrSynchronizable as! String] = kSecAttrSynchronizableAny switch itemClass { case .GenericPassword: query[kSecAttrService as! String] = service #if (!arch(i386) && !arch(x86_64)) || !os(iOS) if let accessGroup = self.accessGroup { query[kSecAttrAccessGroup as! String] = accessGroup } #endif case .InternetPassword: query[kSecAttrServer as! String] = server.host query[kSecAttrPort as! String] = server.port query[kSecAttrProtocol as! String] = protocolType.rawValue query[kSecAttrAuthenticationType as! String] = authenticationType.rawValue } #if os(iOS) if authenticationPrompt != nil { if floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) { query[kSecUseOperationPrompt as! String] = authenticationPrompt } else { println("Unavailable 'authenticationPrompt' attribute on iOS versions prior to 8.0.") } } #endif return query } func attributes(#key: String?, value: NSData) -> ([String: AnyObject], NSError?) { var attributes: [String: AnyObject] if key != nil { attributes = query() attributes[kSecAttrAccount as! String] = key } else { attributes = [String: AnyObject]() } attributes[kSecValueData as! String] = value if label != nil { attributes[kSecAttrLabel as! String] = label } if comment != nil { attributes[kSecAttrComment as! String] = comment } #if os(iOS) let iOS_7_1_or_10_9_2 = NSFoundationVersionNumber_iOS_7_1 #else let iOS_7_1_or_10_9_2 = NSFoundationVersionNumber10_9_2 #endif if let policy = authenticationPolicy { if floor(NSFoundationVersionNumber) > floor(iOS_7_1_or_10_9_2) { var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, accessibility.rawValue, SecAccessControlCreateFlags(policy.rawValue), &error ) if let error = error?.takeUnretainedValue() { return (attributes, error.error) } if accessControl == nil { let message = Status.UnexpectedError.description return (attributes, NSError(domain: KeychainAccessErrorDomain, code: Int(Status.UnexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: message])) } attributes[kSecAttrAccessControl as! String] = accessControl.takeUnretainedValue() } else { #if os(iOS) println("Unavailable 'Touch ID integration' on iOS versions prior to 8.0.") #else println("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") #endif } } else { if floor(NSFoundationVersionNumber) <= floor(iOS_7_1_or_10_9_2) && accessibility == .WhenPasscodeSetThisDeviceOnly { #if os(iOS) println("Unavailable 'Accessibility.WhenPasscodeSetThisDeviceOnly' attribute on iOS versions prior to 8.0.") #else println("Unavailable 'Accessibility.WhenPasscodeSetThisDeviceOnly' attribute on OS X versions prior to 10.10.") #endif } else { attributes[kSecAttrAccessible as! String] = accessibility.rawValue } } attributes[kSecAttrSynchronizable as! String] = synchronizable return (attributes, nil) } } // MARK: extension ItemClass : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecClassGenericPassword as! String: self = GenericPassword case kSecClassInternetPassword as! String: self = InternetPassword default: return nil } } public var rawValue: String { switch self { case GenericPassword: return kSecClassGenericPassword as! String case InternetPassword: return kSecClassInternetPassword as! String } } public var description : String { switch self { case GenericPassword: return "GenericPassword" case InternetPassword: return "InternetPassword" } } } extension ProtocolType : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrProtocolFTP as! String: self = FTP case kSecAttrProtocolFTPAccount as! String: self = FTPAccount case kSecAttrProtocolHTTP as! String: self = HTTP case kSecAttrProtocolIRC as! String: self = IRC case kSecAttrProtocolNNTP as! String: self = NNTP case kSecAttrProtocolPOP3 as! String: self = POP3 case kSecAttrProtocolSMTP as! String: self = SMTP case kSecAttrProtocolSOCKS as! String: self = SOCKS case kSecAttrProtocolIMAP as! String: self = IMAP case kSecAttrProtocolLDAP as! String: self = LDAP case kSecAttrProtocolAppleTalk as! String: self = AppleTalk case kSecAttrProtocolAFP as! String: self = AFP case kSecAttrProtocolTelnet as! String: self = Telnet case kSecAttrProtocolSSH as! String: self = SSH case kSecAttrProtocolFTPS as! String: self = FTPS case kSecAttrProtocolHTTPS as! String: self = HTTPS case kSecAttrProtocolHTTPProxy as! String: self = HTTPProxy case kSecAttrProtocolHTTPSProxy as! String: self = HTTPSProxy case kSecAttrProtocolFTPProxy as! String: self = FTPProxy case kSecAttrProtocolSMB as! String: self = SMB case kSecAttrProtocolRTSP as! String: self = RTSP case kSecAttrProtocolRTSPProxy as! String: self = RTSPProxy case kSecAttrProtocolDAAP as! String: self = DAAP case kSecAttrProtocolEPPC as! String: self = EPPC case kSecAttrProtocolIPP as! String: self = IPP case kSecAttrProtocolNNTPS as! String: self = NNTPS case kSecAttrProtocolLDAPS as! String: self = LDAPS case kSecAttrProtocolTelnetS as! String: self = TelnetS case kSecAttrProtocolIMAPS as! String: self = IMAPS case kSecAttrProtocolIRCS as! String: self = IRCS case kSecAttrProtocolPOP3S as! String: self = POP3S default: return nil } } public var rawValue: String { switch self { case FTP: return kSecAttrProtocolFTP as! String case FTPAccount: return kSecAttrProtocolFTPAccount as! String case HTTP: return kSecAttrProtocolHTTP as! String case IRC: return kSecAttrProtocolIRC as! String case NNTP: return kSecAttrProtocolNNTP as! String case POP3: return kSecAttrProtocolPOP3 as! String case SMTP: return kSecAttrProtocolSMTP as! String case SOCKS: return kSecAttrProtocolSOCKS as! String case IMAP: return kSecAttrProtocolIMAP as! String case LDAP: return kSecAttrProtocolLDAP as! String case AppleTalk: return kSecAttrProtocolAppleTalk as! String case AFP: return kSecAttrProtocolAFP as! String case Telnet: return kSecAttrProtocolTelnet as! String case SSH: return kSecAttrProtocolSSH as! String case FTPS: return kSecAttrProtocolFTPS as! String case HTTPS: return kSecAttrProtocolHTTPS as! String case HTTPProxy: return kSecAttrProtocolHTTPProxy as! String case HTTPSProxy: return kSecAttrProtocolHTTPSProxy as! String case FTPProxy: return kSecAttrProtocolFTPProxy as! String case SMB: return kSecAttrProtocolSMB as! String case RTSP: return kSecAttrProtocolRTSP as! String case RTSPProxy: return kSecAttrProtocolRTSPProxy as! String case DAAP: return kSecAttrProtocolDAAP as! String case EPPC: return kSecAttrProtocolEPPC as! String case IPP: return kSecAttrProtocolIPP as! String case NNTPS: return kSecAttrProtocolNNTPS as! String case LDAPS: return kSecAttrProtocolLDAPS as! String case TelnetS: return kSecAttrProtocolTelnetS as! String case IMAPS: return kSecAttrProtocolIMAPS as! String case IRCS: return kSecAttrProtocolIRCS as! String case POP3S: return kSecAttrProtocolPOP3S as! String } } public var description : String { switch self { case FTP: return "FTP" case FTPAccount: return "FTPAccount" case HTTP: return "HTTP" case IRC: return "IRC" case NNTP: return "NNTP" case POP3: return "POP3" case SMTP: return "SMTP" case SOCKS: return "SOCKS" case IMAP: return "IMAP" case LDAP: return "LDAP" case AppleTalk: return "AppleTalk" case AFP: return "AFP" case Telnet: return "Telnet" case SSH: return "SSH" case FTPS: return "FTPS" case HTTPS: return "HTTPS" case HTTPProxy: return "HTTPProxy" case HTTPSProxy: return "HTTPSProxy" case FTPProxy: return "FTPProxy" case SMB: return "SMB" case RTSP: return "RTSP" case RTSPProxy: return "RTSPProxy" case DAAP: return "DAAP" case EPPC: return "EPPC" case IPP: return "IPP" case NNTPS: return "NNTPS" case LDAPS: return "LDAPS" case TelnetS: return "TelnetS" case IMAPS: return "IMAPS" case IRCS: return "IRCS" case POP3S: return "POP3S" } } } extension AuthenticationType : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrAuthenticationTypeNTLM as! String: self = NTLM case kSecAttrAuthenticationTypeMSN as! String: self = MSN case kSecAttrAuthenticationTypeDPA as! String: self = DPA case kSecAttrAuthenticationTypeRPA as! String: self = RPA case kSecAttrAuthenticationTypeHTTPBasic as! String: self = HTTPBasic case kSecAttrAuthenticationTypeHTTPDigest as! String: self = HTTPDigest case kSecAttrAuthenticationTypeHTMLForm as! String: self = HTMLForm case kSecAttrAuthenticationTypeDefault as! String: self = Default default: return nil } } public var rawValue: String { switch self { case NTLM: return kSecAttrAuthenticationTypeNTLM as! String case MSN: return kSecAttrAuthenticationTypeMSN as! String case DPA: return kSecAttrAuthenticationTypeDPA as! String case RPA: return kSecAttrAuthenticationTypeRPA as! String case HTTPBasic: return kSecAttrAuthenticationTypeHTTPBasic as! String case HTTPDigest: return kSecAttrAuthenticationTypeHTTPDigest as! String case HTMLForm: return kSecAttrAuthenticationTypeHTMLForm as! String case Default: return kSecAttrAuthenticationTypeDefault as! String } } public var description : String { switch self { case NTLM: return "NTLM" case MSN: return "MSN" case DPA: return "DPA" case RPA: return "RPA" case HTTPBasic: return "HTTPBasic" case HTTPDigest: return "HTTPDigest" case HTMLForm: return "HTMLForm" case Default: return "Default" } } } extension Accessibility : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrAccessibleWhenUnlocked as! String: self = WhenUnlocked case kSecAttrAccessibleAfterFirstUnlock as! String: self = AfterFirstUnlock case kSecAttrAccessibleAlways as! String: self = Always case kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as! String: self = WhenPasscodeSetThisDeviceOnly case kSecAttrAccessibleWhenUnlockedThisDeviceOnly as! String: self = WhenUnlockedThisDeviceOnly case kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as! String: self = AfterFirstUnlockThisDeviceOnly case kSecAttrAccessibleAlwaysThisDeviceOnly as! String: self = AlwaysThisDeviceOnly default: return nil } } public var rawValue: String { switch self { case WhenUnlocked: return kSecAttrAccessibleWhenUnlocked as! String case AfterFirstUnlock: return kSecAttrAccessibleAfterFirstUnlock as! String case Always: return kSecAttrAccessibleAlways as! String case WhenPasscodeSetThisDeviceOnly: return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as! String case WhenUnlockedThisDeviceOnly: return kSecAttrAccessibleWhenUnlockedThisDeviceOnly as! String case AfterFirstUnlockThisDeviceOnly: return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as! String case AlwaysThisDeviceOnly: return kSecAttrAccessibleAlwaysThisDeviceOnly as! String } } public var description : String { switch self { case WhenUnlocked: return "WhenUnlocked" case AfterFirstUnlock: return "AfterFirstUnlock" case Always: return "Always" case WhenPasscodeSetThisDeviceOnly: return "WhenPasscodeSetThisDeviceOnly" case WhenUnlockedThisDeviceOnly: return "WhenUnlockedThisDeviceOnly" case AfterFirstUnlockThisDeviceOnly: return "AfterFirstUnlockThisDeviceOnly" case AlwaysThisDeviceOnly: return "AlwaysThisDeviceOnly" } } } extension AuthenticationPolicy : RawRepresentable, Printable { public init?(rawValue: Int) { var flags = SecAccessControlCreateFlags.UserPresence switch rawValue { case flags.rawValue: self = UserPresence default: return nil } } public var rawValue: Int { switch self { case UserPresence: return SecAccessControlCreateFlags.UserPresence.rawValue } } public var description : String { switch self { case UserPresence: return "UserPresence" } } } extension FailableOf: Printable, DebugPrintable { public var description: String { switch self { case .Success(let success): if let value = success.value { return "\(value)" } return "nil" case .Failure(let error): return "\(error.localizedDescription)" } } public var debugDescription: String { switch self { case .Success(let success): return "\(success.value)" case .Failure(let error): return "\(error)" } } } extension CFError { var error: NSError { var domain = CFErrorGetDomain(self) as String var code = CFErrorGetCode(self) var userInfo = CFErrorCopyUserInfo(self) as [NSObject: AnyObject] return NSError(domain: domain, code: code, userInfo: userInfo) } } public enum Status : OSStatus { case Success case Unimplemented case Param case Allocate case NotAvailable case ReadOnly case AuthFailed case NoSuchKeychain case InvalidKeychain case DuplicateKeychain case DuplicateCallback case InvalidCallback case DuplicateItem case ItemNotFound case BufferTooSmall case DataTooLarge case NoSuchAttr case InvalidItemRef case InvalidSearchRef case NoSuchClass case NoDefaultKeychain case InteractionNotAllowed case ReadOnlyAttr case WrongSecVersion case KeySizeNotAllowed case NoStorageModule case NoCertificateModule case NoPolicyModule case InteractionRequired case DataNotAvailable case DataNotModifiable case CreateChainFailed case InvalidPrefsDomain case ACLNotSimple case PolicyNotFound case InvalidTrustSetting case NoAccessForItem case InvalidOwnerEdit case TrustNotAvailable case UnsupportedFormat case UnknownFormat case KeyIsSensitive case MultiplePrivKeys case PassphraseRequired case InvalidPasswordRef case InvalidTrustSettings case NoTrustSettings case Pkcs12VerifyFailure case InvalidCertificate case NotSigner case PolicyDenied case InvalidKey case Decode case Internal case UnsupportedAlgorithm case UnsupportedOperation case UnsupportedPadding case ItemInvalidKey case ItemInvalidKeyType case ItemInvalidValue case ItemClassMissing case ItemMatchUnsupported case UseItemListUnsupported case UseKeychainUnsupported case UseKeychainListUnsupported case ReturnDataUnsupported case ReturnAttributesUnsupported case ReturnRefUnsupported case ReturnPersitentRefUnsupported case ValueRefUnsupported case ValuePersistentRefUnsupported case ReturnMissingPointer case MatchLimitUnsupported case ItemIllegalQuery case WaitForCallback case MissingEntitlement case UpgradePending case MPSignatureInvalid case OTRTooOld case OTRIDTooNew case ServiceNotAvailable case InsufficientClientID case DeviceReset case DeviceFailed case AppleAddAppACLSubject case ApplePublicKeyIncomplete case AppleSignatureMismatch case AppleInvalidKeyStartDate case AppleInvalidKeyEndDate case ConversionError case AppleSSLv2Rollback case DiskFull case QuotaExceeded case FileTooBig case InvalidDatabaseBlob case InvalidKeyBlob case IncompatibleDatabaseBlob case IncompatibleKeyBlob case HostNameMismatch case UnknownCriticalExtensionFlag case NoBasicConstraints case NoBasicConstraintsCA case InvalidAuthorityKeyID case InvalidSubjectKeyID case InvalidKeyUsageForPolicy case InvalidExtendedKeyUsage case InvalidIDLinkage case PathLengthConstraintExceeded case InvalidRoot case CRLExpired case CRLNotValidYet case CRLNotFound case CRLServerDown case CRLBadURI case UnknownCertExtension case UnknownCRLExtension case CRLNotTrusted case CRLPolicyFailed case IDPFailure case SMIMEEmailAddressesNotFound case SMIMEBadExtendedKeyUsage case SMIMEBadKeyUsage case SMIMEKeyUsageNotCritical case SMIMENoEmailAddress case SMIMESubjAltNameNotCritical case SSLBadExtendedKeyUsage case OCSPBadResponse case OCSPBadRequest case OCSPUnavailable case OCSPStatusUnrecognized case EndOfData case IncompleteCertRevocationCheck case NetworkFailure case OCSPNotTrustedToAnchor case RecordModified case OCSPSignatureError case OCSPNoSigner case OCSPResponderMalformedReq case OCSPResponderInternalError case OCSPResponderTryLater case OCSPResponderSignatureRequired case OCSPResponderUnauthorized case OCSPResponseNonceMismatch case CodeSigningBadCertChainLength case CodeSigningNoBasicConstraints case CodeSigningBadPathLengthConstraint case CodeSigningNoExtendedKeyUsage case CodeSigningDevelopment case ResourceSignBadCertChainLength case ResourceSignBadExtKeyUsage case TrustSettingDeny case InvalidSubjectName case UnknownQualifiedCertStatement case MobileMeRequestQueued case MobileMeRequestRedirected case MobileMeServerError case MobileMeServerNotAvailable case MobileMeServerAlreadyExists case MobileMeServerServiceErr case MobileMeRequestAlreadyPending case MobileMeNoRequestPending case MobileMeCSRVerifyFailure case MobileMeFailedConsistencyCheck case NotInitialized case InvalidHandleUsage case PVCReferentNotFound case FunctionIntegrityFail case InternalError case MemoryError case InvalidData case MDSError case InvalidPointer case SelfCheckFailed case FunctionFailed case ModuleManifestVerifyFailed case InvalidGUID case InvalidHandle case InvalidDBList case InvalidPassthroughID case InvalidNetworkAddress case CRLAlreadySigned case InvalidNumberOfFields case VerificationFailure case UnknownTag case InvalidSignature case InvalidName case InvalidCertificateRef case InvalidCertificateGroup case TagNotFound case InvalidQuery case InvalidValue case CallbackFailed case ACLDeleteFailed case ACLReplaceFailed case ACLAddFailed case ACLChangeFailed case InvalidAccessCredentials case InvalidRecord case InvalidACL case InvalidSampleValue case IncompatibleVersion case PrivilegeNotGranted case InvalidScope case PVCAlreadyConfigured case InvalidPVC case EMMLoadFailed case EMMUnloadFailed case AddinLoadFailed case InvalidKeyRef case InvalidKeyHierarchy case AddinUnloadFailed case LibraryReferenceNotFound case InvalidAddinFunctionTable case InvalidServiceMask case ModuleNotLoaded case InvalidSubServiceID case AttributeNotInContext case ModuleManagerInitializeFailed case ModuleManagerNotFound case EventNotificationCallbackNotFound case InputLengthError case OutputLengthError case PrivilegeNotSupported case DeviceError case AttachHandleBusy case NotLoggedIn case AlgorithmMismatch case KeyUsageIncorrect case KeyBlobTypeIncorrect case KeyHeaderInconsistent case UnsupportedKeyFormat case UnsupportedKeySize case InvalidKeyUsageMask case UnsupportedKeyUsageMask case InvalidKeyAttributeMask case UnsupportedKeyAttributeMask case InvalidKeyLabel case UnsupportedKeyLabel case InvalidKeyFormat case UnsupportedVectorOfBuffers case InvalidInputVector case InvalidOutputVector case InvalidContext case InvalidAlgorithm case InvalidAttributeKey case MissingAttributeKey case InvalidAttributeInitVector case MissingAttributeInitVector case InvalidAttributeSalt case MissingAttributeSalt case InvalidAttributePadding case MissingAttributePadding case InvalidAttributeRandom case MissingAttributeRandom case InvalidAttributeSeed case MissingAttributeSeed case InvalidAttributePassphrase case MissingAttributePassphrase case InvalidAttributeKeyLength case MissingAttributeKeyLength case InvalidAttributeBlockSize case MissingAttributeBlockSize case InvalidAttributeOutputSize case MissingAttributeOutputSize case InvalidAttributeRounds case MissingAttributeRounds case InvalidAlgorithmParms case MissingAlgorithmParms case InvalidAttributeLabel case MissingAttributeLabel case InvalidAttributeKeyType case MissingAttributeKeyType case InvalidAttributeMode case MissingAttributeMode case InvalidAttributeEffectiveBits case MissingAttributeEffectiveBits case InvalidAttributeStartDate case MissingAttributeStartDate case InvalidAttributeEndDate case MissingAttributeEndDate case InvalidAttributeVersion case MissingAttributeVersion case InvalidAttributePrime case MissingAttributePrime case InvalidAttributeBase case MissingAttributeBase case InvalidAttributeSubprime case MissingAttributeSubprime case InvalidAttributeIterationCount case MissingAttributeIterationCount case InvalidAttributeDLDBHandle case MissingAttributeDLDBHandle case InvalidAttributeAccessCredentials case MissingAttributeAccessCredentials case InvalidAttributePublicKeyFormat case MissingAttributePublicKeyFormat case InvalidAttributePrivateKeyFormat case MissingAttributePrivateKeyFormat case InvalidAttributeSymmetricKeyFormat case MissingAttributeSymmetricKeyFormat case InvalidAttributeWrappedKeyFormat case MissingAttributeWrappedKeyFormat case StagedOperationInProgress case StagedOperationNotStarted case VerifyFailed case QuerySizeUnknown case BlockSizeMismatch case PublicKeyInconsistent case DeviceVerifyFailed case InvalidLoginName case AlreadyLoggedIn case InvalidDigestAlgorithm case InvalidCRLGroup case CertificateCannotOperate case CertificateExpired case CertificateNotValidYet case CertificateRevoked case CertificateSuspended case InsufficientCredentials case InvalidAction case InvalidAuthority case VerifyActionFailed case InvalidCertAuthority case InvaldCRLAuthority case InvalidCRLEncoding case InvalidCRLType case InvalidCRL case InvalidFormType case InvalidID case InvalidIdentifier case InvalidIndex case InvalidPolicyIdentifiers case InvalidTimeString case InvalidReason case InvalidRequestInputs case InvalidResponseVector case InvalidStopOnPolicy case InvalidTuple case MultipleValuesUnsupported case NotTrusted case NoDefaultAuthority case RejectedForm case RequestLost case RequestRejected case UnsupportedAddressType case UnsupportedService case InvalidTupleGroup case InvalidBaseACLs case InvalidTupleCredendtials case InvalidEncoding case InvalidValidityPeriod case InvalidRequestor case RequestDescriptor case InvalidBundleInfo case InvalidCRLIndex case NoFieldValues case UnsupportedFieldFormat case UnsupportedIndexInfo case UnsupportedLocality case UnsupportedNumAttributes case UnsupportedNumIndexes case UnsupportedNumRecordTypes case FieldSpecifiedMultiple case IncompatibleFieldFormat case InvalidParsingModule case DatabaseLocked case DatastoreIsOpen case MissingValue case UnsupportedQueryLimits case UnsupportedNumSelectionPreds case UnsupportedOperator case InvalidDBLocation case InvalidAccessRequest case InvalidIndexInfo case InvalidNewOwner case InvalidModifyMode case UnexpectedError } extension Status : RawRepresentable, Printable { public init?(rawValue: OSStatus) { switch rawValue { case 0: self = Success case -4: self = Unimplemented case -50: self = Param case -108: self = Allocate case -25291: self = NotAvailable case -25292: self = ReadOnly case -25293: self = AuthFailed case -25294: self = NoSuchKeychain case -25295: self = InvalidKeychain case -25296: self = DuplicateKeychain case -25297: self = DuplicateCallback case -25298: self = InvalidCallback case -25299: self = DuplicateItem case -25300: self = ItemNotFound case -25301: self = BufferTooSmall case -25302: self = DataTooLarge case -25303: self = NoSuchAttr case -25304: self = InvalidItemRef case -25305: self = InvalidSearchRef case -25306: self = NoSuchClass case -25307: self = NoDefaultKeychain case -25308: self = InteractionNotAllowed case -25309: self = ReadOnlyAttr case -25310: self = WrongSecVersion case -25311: self = KeySizeNotAllowed case -25312: self = NoStorageModule case -25313: self = NoCertificateModule case -25314: self = NoPolicyModule case -25315: self = InteractionRequired case -25316: self = DataNotAvailable case -25317: self = DataNotModifiable case -25318: self = CreateChainFailed case -25319: self = InvalidPrefsDomain case -25240: self = ACLNotSimple case -25241: self = PolicyNotFound case -25242: self = InvalidTrustSetting case -25243: self = NoAccessForItem case -25244: self = InvalidOwnerEdit case -25245: self = TrustNotAvailable case -25256: self = UnsupportedFormat case -25257: self = UnknownFormat case -25258: self = KeyIsSensitive case -25259: self = MultiplePrivKeys case -25260: self = PassphraseRequired case -25261: self = InvalidPasswordRef case -25262: self = InvalidTrustSettings case -25263: self = NoTrustSettings case -25264: self = Pkcs12VerifyFailure case -26265: self = InvalidCertificate case -26267: self = NotSigner case -26270: self = PolicyDenied case -26274: self = InvalidKey case -26275: self = Decode case -26276: self = Internal case -26268: self = UnsupportedAlgorithm case -26271: self = UnsupportedOperation case -26273: self = UnsupportedPadding case -34000: self = ItemInvalidKey case -34001: self = ItemInvalidKeyType case -34002: self = ItemInvalidValue case -34003: self = ItemClassMissing case -34004: self = ItemMatchUnsupported case -34005: self = UseItemListUnsupported case -34006: self = UseKeychainUnsupported case -34007: self = UseKeychainListUnsupported case -34008: self = ReturnDataUnsupported case -34009: self = ReturnAttributesUnsupported case -34010: self = ReturnRefUnsupported case -34010: self = ReturnPersitentRefUnsupported case -34012: self = ValueRefUnsupported case -34013: self = ValuePersistentRefUnsupported case -34014: self = ReturnMissingPointer case -34015: self = MatchLimitUnsupported case -34016: self = ItemIllegalQuery case -34017: self = WaitForCallback case -34018: self = MissingEntitlement case -34019: self = UpgradePending case -25327: self = MPSignatureInvalid case -25328: self = OTRTooOld case -25329: self = OTRIDTooNew case -67585: self = ServiceNotAvailable case -67586: self = InsufficientClientID case -67587: self = DeviceReset case -67588: self = DeviceFailed case -67589: self = AppleAddAppACLSubject case -67590: self = ApplePublicKeyIncomplete case -67591: self = AppleSignatureMismatch case -67592: self = AppleInvalidKeyStartDate case -67593: self = AppleInvalidKeyEndDate case -67594: self = ConversionError case -67595: self = AppleSSLv2Rollback case -34: self = DiskFull case -67596: self = QuotaExceeded case -67597: self = FileTooBig case -67598: self = InvalidDatabaseBlob case -67599: self = InvalidKeyBlob case -67600: self = IncompatibleDatabaseBlob case -67601: self = IncompatibleKeyBlob case -67602: self = HostNameMismatch case -67603: self = UnknownCriticalExtensionFlag case -67604: self = NoBasicConstraints case -67605: self = NoBasicConstraintsCA case -67606: self = InvalidAuthorityKeyID case -67607: self = InvalidSubjectKeyID case -67608: self = InvalidKeyUsageForPolicy case -67609: self = InvalidExtendedKeyUsage case -67610: self = InvalidIDLinkage case -67611: self = PathLengthConstraintExceeded case -67612: self = InvalidRoot case -67613: self = CRLExpired case -67614: self = CRLNotValidYet case -67615: self = CRLNotFound case -67616: self = CRLServerDown case -67617: self = CRLBadURI case -67618: self = UnknownCertExtension case -67619: self = UnknownCRLExtension case -67620: self = CRLNotTrusted case -67621: self = CRLPolicyFailed case -67622: self = IDPFailure case -67623: self = SMIMEEmailAddressesNotFound case -67624: self = SMIMEBadExtendedKeyUsage case -67625: self = SMIMEBadKeyUsage case -67626: self = SMIMEKeyUsageNotCritical case -67627: self = SMIMENoEmailAddress case -67628: self = SMIMESubjAltNameNotCritical case -67629: self = SSLBadExtendedKeyUsage case -67630: self = OCSPBadResponse case -67631: self = OCSPBadRequest case -67632: self = OCSPUnavailable case -67633: self = OCSPStatusUnrecognized case -67634: self = EndOfData case -67635: self = IncompleteCertRevocationCheck case -67636: self = NetworkFailure case -67637: self = OCSPNotTrustedToAnchor case -67638: self = RecordModified case -67639: self = OCSPSignatureError case -67640: self = OCSPNoSigner case -67641: self = OCSPResponderMalformedReq case -67642: self = OCSPResponderInternalError case -67643: self = OCSPResponderTryLater case -67644: self = OCSPResponderSignatureRequired case -67645: self = OCSPResponderUnauthorized case -67646: self = OCSPResponseNonceMismatch case -67647: self = CodeSigningBadCertChainLength case -67648: self = CodeSigningNoBasicConstraints case -67649: self = CodeSigningBadPathLengthConstraint case -67650: self = CodeSigningNoExtendedKeyUsage case -67651: self = CodeSigningDevelopment case -67652: self = ResourceSignBadCertChainLength case -67653: self = ResourceSignBadExtKeyUsage case -67654: self = TrustSettingDeny case -67655: self = InvalidSubjectName case -67656: self = UnknownQualifiedCertStatement case -67657: self = MobileMeRequestQueued case -67658: self = MobileMeRequestRedirected case -67659: self = MobileMeServerError case -67660: self = MobileMeServerNotAvailable case -67661: self = MobileMeServerAlreadyExists case -67662: self = MobileMeServerServiceErr case -67663: self = MobileMeRequestAlreadyPending case -67664: self = MobileMeNoRequestPending case -67665: self = MobileMeCSRVerifyFailure case -67666: self = MobileMeFailedConsistencyCheck case -67667: self = NotInitialized case -67668: self = InvalidHandleUsage case -67669: self = PVCReferentNotFound case -67670: self = FunctionIntegrityFail case -67671: self = InternalError case -67672: self = MemoryError case -67673: self = InvalidData case -67674: self = MDSError case -67675: self = InvalidPointer case -67676: self = SelfCheckFailed case -67677: self = FunctionFailed case -67678: self = ModuleManifestVerifyFailed case -67679: self = InvalidGUID case -67680: self = InvalidHandle case -67681: self = InvalidDBList case -67682: self = InvalidPassthroughID case -67683: self = InvalidNetworkAddress case -67684: self = CRLAlreadySigned case -67685: self = InvalidNumberOfFields case -67686: self = VerificationFailure case -67687: self = UnknownTag case -67688: self = InvalidSignature case -67689: self = InvalidName case -67690: self = InvalidCertificateRef case -67691: self = InvalidCertificateGroup case -67692: self = TagNotFound case -67693: self = InvalidQuery case -67694: self = InvalidValue case -67695: self = CallbackFailed case -67696: self = ACLDeleteFailed case -67697: self = ACLReplaceFailed case -67698: self = ACLAddFailed case -67699: self = ACLChangeFailed case -67700: self = InvalidAccessCredentials case -67701: self = InvalidRecord case -67702: self = InvalidACL case -67703: self = InvalidSampleValue case -67704: self = IncompatibleVersion case -67705: self = PrivilegeNotGranted case -67706: self = InvalidScope case -67707: self = PVCAlreadyConfigured case -67708: self = InvalidPVC case -67709: self = EMMLoadFailed case -67710: self = EMMUnloadFailed case -67711: self = AddinLoadFailed case -67712: self = InvalidKeyRef case -67713: self = InvalidKeyHierarchy case -67714: self = AddinUnloadFailed case -67715: self = LibraryReferenceNotFound case -67716: self = InvalidAddinFunctionTable case -67717: self = InvalidServiceMask case -67718: self = ModuleNotLoaded case -67719: self = InvalidSubServiceID case -67720: self = AttributeNotInContext case -67721: self = ModuleManagerInitializeFailed case -67722: self = ModuleManagerNotFound case -67723: self = EventNotificationCallbackNotFound case -67724: self = InputLengthError case -67725: self = OutputLengthError case -67726: self = PrivilegeNotSupported case -67727: self = DeviceError case -67728: self = AttachHandleBusy case -67729: self = NotLoggedIn case -67730: self = AlgorithmMismatch case -67731: self = KeyUsageIncorrect case -67732: self = KeyBlobTypeIncorrect case -67733: self = KeyHeaderInconsistent case -67734: self = UnsupportedKeyFormat case -67735: self = UnsupportedKeySize case -67736: self = InvalidKeyUsageMask case -67737: self = UnsupportedKeyUsageMask case -67738: self = InvalidKeyAttributeMask case -67739: self = UnsupportedKeyAttributeMask case -67740: self = InvalidKeyLabel case -67741: self = UnsupportedKeyLabel case -67742: self = InvalidKeyFormat case -67743: self = UnsupportedVectorOfBuffers case -67744: self = InvalidInputVector case -67745: self = InvalidOutputVector case -67746: self = InvalidContext case -67747: self = InvalidAlgorithm case -67748: self = InvalidAttributeKey case -67749: self = MissingAttributeKey case -67750: self = InvalidAttributeInitVector case -67751: self = MissingAttributeInitVector case -67752: self = InvalidAttributeSalt case -67753: self = MissingAttributeSalt case -67754: self = InvalidAttributePadding case -67755: self = MissingAttributePadding case -67756: self = InvalidAttributeRandom case -67757: self = MissingAttributeRandom case -67758: self = InvalidAttributeSeed case -67759: self = MissingAttributeSeed case -67760: self = InvalidAttributePassphrase case -67761: self = MissingAttributePassphrase case -67762: self = InvalidAttributeKeyLength case -67763: self = MissingAttributeKeyLength case -67764: self = InvalidAttributeBlockSize case -67765: self = MissingAttributeBlockSize case -67766: self = InvalidAttributeOutputSize case -67767: self = MissingAttributeOutputSize case -67768: self = InvalidAttributeRounds case -67769: self = MissingAttributeRounds case -67770: self = InvalidAlgorithmParms case -67771: self = MissingAlgorithmParms case -67772: self = InvalidAttributeLabel case -67773: self = MissingAttributeLabel case -67774: self = InvalidAttributeKeyType case -67775: self = MissingAttributeKeyType case -67776: self = InvalidAttributeMode case -67777: self = MissingAttributeMode case -67778: self = InvalidAttributeEffectiveBits case -67779: self = MissingAttributeEffectiveBits case -67780: self = InvalidAttributeStartDate case -67781: self = MissingAttributeStartDate case -67782: self = InvalidAttributeEndDate case -67783: self = MissingAttributeEndDate case -67784: self = InvalidAttributeVersion case -67785: self = MissingAttributeVersion case -67786: self = InvalidAttributePrime case -67787: self = MissingAttributePrime case -67788: self = InvalidAttributeBase case -67789: self = MissingAttributeBase case -67790: self = InvalidAttributeSubprime case -67791: self = MissingAttributeSubprime case -67792: self = InvalidAttributeIterationCount case -67793: self = MissingAttributeIterationCount case -67794: self = InvalidAttributeDLDBHandle case -67795: self = MissingAttributeDLDBHandle case -67796: self = InvalidAttributeAccessCredentials case -67797: self = MissingAttributeAccessCredentials case -67798: self = InvalidAttributePublicKeyFormat case -67799: self = MissingAttributePublicKeyFormat case -67800: self = InvalidAttributePrivateKeyFormat case -67801: self = MissingAttributePrivateKeyFormat case -67802: self = InvalidAttributeSymmetricKeyFormat case -67803: self = MissingAttributeSymmetricKeyFormat case -67804: self = InvalidAttributeWrappedKeyFormat case -67805: self = MissingAttributeWrappedKeyFormat case -67806: self = StagedOperationInProgress case -67807: self = StagedOperationNotStarted case -67808: self = VerifyFailed case -67809: self = QuerySizeUnknown case -67810: self = BlockSizeMismatch case -67811: self = PublicKeyInconsistent case -67812: self = DeviceVerifyFailed case -67813: self = InvalidLoginName case -67814: self = AlreadyLoggedIn case -67815: self = InvalidDigestAlgorithm case -67816: self = InvalidCRLGroup case -67817: self = CertificateCannotOperate case -67818: self = CertificateExpired case -67819: self = CertificateNotValidYet case -67820: self = CertificateRevoked case -67821: self = CertificateSuspended case -67822: self = InsufficientCredentials case -67823: self = InvalidAction case -67824: self = InvalidAuthority case -67825: self = VerifyActionFailed case -67826: self = InvalidCertAuthority case -67827: self = InvaldCRLAuthority case -67828: self = InvalidCRLEncoding case -67829: self = InvalidCRLType case -67830: self = InvalidCRL case -67831: self = InvalidFormType case -67832: self = InvalidID case -67833: self = InvalidIdentifier case -67834: self = InvalidIndex case -67835: self = InvalidPolicyIdentifiers case -67836: self = InvalidTimeString case -67837: self = InvalidReason case -67838: self = InvalidRequestInputs case -67839: self = InvalidResponseVector case -67840: self = InvalidStopOnPolicy case -67841: self = InvalidTuple case -67842: self = MultipleValuesUnsupported case -67843: self = NotTrusted case -67844: self = NoDefaultAuthority case -67845: self = RejectedForm case -67846: self = RequestLost case -67847: self = RequestRejected case -67848: self = UnsupportedAddressType case -67849: self = UnsupportedService case -67850: self = InvalidTupleGroup case -67851: self = InvalidBaseACLs case -67852: self = InvalidTupleCredendtials case -67853: self = InvalidEncoding case -67854: self = InvalidValidityPeriod case -67855: self = InvalidRequestor case -67856: self = RequestDescriptor case -67857: self = InvalidBundleInfo case -67858: self = InvalidCRLIndex case -67859: self = NoFieldValues case -67860: self = UnsupportedFieldFormat case -67861: self = UnsupportedIndexInfo case -67862: self = UnsupportedLocality case -67863: self = UnsupportedNumAttributes case -67864: self = UnsupportedNumIndexes case -67865: self = UnsupportedNumRecordTypes case -67866: self = FieldSpecifiedMultiple case -67867: self = IncompatibleFieldFormat case -67868: self = InvalidParsingModule case -67869: self = DatabaseLocked case -67870: self = DatastoreIsOpen case -67871: self = MissingValue case -67872: self = UnsupportedQueryLimits case -67873: self = UnsupportedNumSelectionPreds case -67874: self = UnsupportedOperator case -67875: self = InvalidDBLocation case -67876: self = InvalidAccessRequest case -67877: self = InvalidIndexInfo case -67878: self = InvalidNewOwner case -67879: self = InvalidModifyMode default: self = UnexpectedError } } public var rawValue: OSStatus { switch self { case Success: return 0 case Unimplemented: return -4 case Param: return -50 case Allocate: return -108 case NotAvailable: return -25291 case ReadOnly: return -25292 case AuthFailed: return -25293 case NoSuchKeychain: return -25294 case InvalidKeychain: return -25295 case DuplicateKeychain: return -25296 case DuplicateCallback: return -25297 case InvalidCallback: return -25298 case DuplicateItem: return -25299 case ItemNotFound: return -25300 case BufferTooSmall: return -25301 case DataTooLarge: return -25302 case NoSuchAttr: return -25303 case InvalidItemRef: return -25304 case InvalidSearchRef: return -25305 case NoSuchClass: return -25306 case NoDefaultKeychain: return -25307 case InteractionNotAllowed: return -25308 case ReadOnlyAttr: return -25309 case WrongSecVersion: return -25310 case KeySizeNotAllowed: return -25311 case NoStorageModule: return -25312 case NoCertificateModule: return -25313 case NoPolicyModule: return -25314 case InteractionRequired: return -25315 case DataNotAvailable: return -25316 case DataNotModifiable: return -25317 case CreateChainFailed: return -25318 case InvalidPrefsDomain: return -25319 case ACLNotSimple: return -25240 case PolicyNotFound: return -25241 case InvalidTrustSetting: return -25242 case NoAccessForItem: return -25243 case InvalidOwnerEdit: return -25244 case TrustNotAvailable: return -25245 case UnsupportedFormat: return -25256 case UnknownFormat: return -25257 case KeyIsSensitive: return -25258 case MultiplePrivKeys: return -25259 case PassphraseRequired: return -25260 case InvalidPasswordRef: return -25261 case InvalidTrustSettings: return -25262 case NoTrustSettings: return -25263 case Pkcs12VerifyFailure: return -25264 case InvalidCertificate: return -26265 case NotSigner: return -26267 case PolicyDenied: return -26270 case InvalidKey: return -26274 case Decode: return -26275 case Internal: return -26276 case UnsupportedAlgorithm: return -26268 case UnsupportedOperation: return -26271 case UnsupportedPadding: return -26273 case ItemInvalidKey: return -34000 case ItemInvalidKeyType: return -34001 case ItemInvalidValue: return -34002 case ItemClassMissing: return -34003 case ItemMatchUnsupported: return -34004 case UseItemListUnsupported: return -34005 case UseKeychainUnsupported: return -34006 case UseKeychainListUnsupported: return -34007 case ReturnDataUnsupported: return -34008 case ReturnAttributesUnsupported: return -34009 case ReturnRefUnsupported: return -34010 case ReturnPersitentRefUnsupported: return -34010 case ValueRefUnsupported: return -34012 case ValuePersistentRefUnsupported: return -34013 case ReturnMissingPointer: return -34014 case MatchLimitUnsupported: return -34015 case ItemIllegalQuery: return -34016 case WaitForCallback: return -34017 case MissingEntitlement: return -34018 case UpgradePending: return -34019 case MPSignatureInvalid: return -25327 case OTRTooOld: return -25328 case OTRIDTooNew: return -25329 case ServiceNotAvailable: return -67585 case InsufficientClientID: return -67586 case DeviceReset: return -67587 case DeviceFailed: return -67588 case AppleAddAppACLSubject: return -67589 case ApplePublicKeyIncomplete: return -67590 case AppleSignatureMismatch: return -67591 case AppleInvalidKeyStartDate: return -67592 case AppleInvalidKeyEndDate: return -67593 case ConversionError: return -67594 case AppleSSLv2Rollback: return -67595 case DiskFull: return -34 case QuotaExceeded: return -67596 case FileTooBig: return -67597 case InvalidDatabaseBlob: return -67598 case InvalidKeyBlob: return -67599 case IncompatibleDatabaseBlob: return -67600 case IncompatibleKeyBlob: return -67601 case HostNameMismatch: return -67602 case UnknownCriticalExtensionFlag: return -67603 case NoBasicConstraints: return -67604 case NoBasicConstraintsCA: return -67605 case InvalidAuthorityKeyID: return -67606 case InvalidSubjectKeyID: return -67607 case InvalidKeyUsageForPolicy: return -67608 case InvalidExtendedKeyUsage: return -67609 case InvalidIDLinkage: return -67610 case PathLengthConstraintExceeded: return -67611 case InvalidRoot: return -67612 case CRLExpired: return -67613 case CRLNotValidYet: return -67614 case CRLNotFound: return -67615 case CRLServerDown: return -67616 case CRLBadURI: return -67617 case UnknownCertExtension: return -67618 case UnknownCRLExtension: return -67619 case CRLNotTrusted: return -67620 case CRLPolicyFailed: return -67621 case IDPFailure: return -67622 case SMIMEEmailAddressesNotFound: return -67623 case SMIMEBadExtendedKeyUsage: return -67624 case SMIMEBadKeyUsage: return -67625 case SMIMEKeyUsageNotCritical: return -67626 case SMIMENoEmailAddress: return -67627 case SMIMESubjAltNameNotCritical: return -67628 case SSLBadExtendedKeyUsage: return -67629 case OCSPBadResponse: return -67630 case OCSPBadRequest: return -67631 case OCSPUnavailable: return -67632 case OCSPStatusUnrecognized: return -67633 case EndOfData: return -67634 case IncompleteCertRevocationCheck: return -67635 case NetworkFailure: return -67636 case OCSPNotTrustedToAnchor: return -67637 case RecordModified: return -67638 case OCSPSignatureError: return -67639 case OCSPNoSigner: return -67640 case OCSPResponderMalformedReq: return -67641 case OCSPResponderInternalError: return -67642 case OCSPResponderTryLater: return -67643 case OCSPResponderSignatureRequired: return -67644 case OCSPResponderUnauthorized: return -67645 case OCSPResponseNonceMismatch: return -67646 case CodeSigningBadCertChainLength: return -67647 case CodeSigningNoBasicConstraints: return -67648 case CodeSigningBadPathLengthConstraint: return -67649 case CodeSigningNoExtendedKeyUsage: return -67650 case CodeSigningDevelopment: return -67651 case ResourceSignBadCertChainLength: return -67652 case ResourceSignBadExtKeyUsage: return -67653 case TrustSettingDeny: return -67654 case InvalidSubjectName: return -67655 case UnknownQualifiedCertStatement: return -67656 case MobileMeRequestQueued: return -67657 case MobileMeRequestRedirected: return -67658 case MobileMeServerError: return -67659 case MobileMeServerNotAvailable: return -67660 case MobileMeServerAlreadyExists: return -67661 case MobileMeServerServiceErr: return -67662 case MobileMeRequestAlreadyPending: return -67663 case MobileMeNoRequestPending: return -67664 case MobileMeCSRVerifyFailure: return -67665 case MobileMeFailedConsistencyCheck: return -67666 case NotInitialized: return -67667 case InvalidHandleUsage: return -67668 case PVCReferentNotFound: return -67669 case FunctionIntegrityFail: return -67670 case InternalError: return -67671 case MemoryError: return -67672 case InvalidData: return -67673 case MDSError: return -67674 case InvalidPointer: return -67675 case SelfCheckFailed: return -67676 case FunctionFailed: return -67677 case ModuleManifestVerifyFailed: return -67678 case InvalidGUID: return -67679 case InvalidHandle: return -67680 case InvalidDBList: return -67681 case InvalidPassthroughID: return -67682 case InvalidNetworkAddress: return -67683 case CRLAlreadySigned: return -67684 case InvalidNumberOfFields: return -67685 case VerificationFailure: return -67686 case UnknownTag: return -67687 case InvalidSignature: return -67688 case InvalidName: return -67689 case InvalidCertificateRef: return -67690 case InvalidCertificateGroup: return -67691 case TagNotFound: return -67692 case InvalidQuery: return -67693 case InvalidValue: return -67694 case CallbackFailed: return -67695 case ACLDeleteFailed: return -67696 case ACLReplaceFailed: return -67697 case ACLAddFailed: return -67698 case ACLChangeFailed: return -67699 case InvalidAccessCredentials: return -67700 case InvalidRecord: return -67701 case InvalidACL: return -67702 case InvalidSampleValue: return -67703 case IncompatibleVersion: return -67704 case PrivilegeNotGranted: return -67705 case InvalidScope: return -67706 case PVCAlreadyConfigured: return -67707 case InvalidPVC: return -67708 case EMMLoadFailed: return -67709 case EMMUnloadFailed: return -67710 case AddinLoadFailed: return -67711 case InvalidKeyRef: return -67712 case InvalidKeyHierarchy: return -67713 case AddinUnloadFailed: return -67714 case LibraryReferenceNotFound: return -67715 case InvalidAddinFunctionTable: return -67716 case InvalidServiceMask: return -67717 case ModuleNotLoaded: return -67718 case InvalidSubServiceID: return -67719 case AttributeNotInContext: return -67720 case ModuleManagerInitializeFailed: return -67721 case ModuleManagerNotFound: return -67722 case EventNotificationCallbackNotFound: return -67723 case InputLengthError: return -67724 case OutputLengthError: return -67725 case PrivilegeNotSupported: return -67726 case DeviceError: return -67727 case AttachHandleBusy: return -67728 case NotLoggedIn: return -67729 case AlgorithmMismatch: return -67730 case KeyUsageIncorrect: return -67731 case KeyBlobTypeIncorrect: return -67732 case KeyHeaderInconsistent: return -67733 case UnsupportedKeyFormat: return -67734 case UnsupportedKeySize: return -67735 case InvalidKeyUsageMask: return -67736 case UnsupportedKeyUsageMask: return -67737 case InvalidKeyAttributeMask: return -67738 case UnsupportedKeyAttributeMask: return -67739 case InvalidKeyLabel: return -67740 case UnsupportedKeyLabel: return -67741 case InvalidKeyFormat: return -67742 case UnsupportedVectorOfBuffers: return -67743 case InvalidInputVector: return -67744 case InvalidOutputVector: return -67745 case InvalidContext: return -67746 case InvalidAlgorithm: return -67747 case InvalidAttributeKey: return -67748 case MissingAttributeKey: return -67749 case InvalidAttributeInitVector: return -67750 case MissingAttributeInitVector: return -67751 case InvalidAttributeSalt: return -67752 case MissingAttributeSalt: return -67753 case InvalidAttributePadding: return -67754 case MissingAttributePadding: return -67755 case InvalidAttributeRandom: return -67756 case MissingAttributeRandom: return -67757 case InvalidAttributeSeed: return -67758 case MissingAttributeSeed: return -67759 case InvalidAttributePassphrase: return -67760 case MissingAttributePassphrase: return -67761 case InvalidAttributeKeyLength: return -67762 case MissingAttributeKeyLength: return -67763 case InvalidAttributeBlockSize: return -67764 case MissingAttributeBlockSize: return -67765 case InvalidAttributeOutputSize: return -67766 case MissingAttributeOutputSize: return -67767 case InvalidAttributeRounds: return -67768 case MissingAttributeRounds: return -67769 case InvalidAlgorithmParms: return -67770 case MissingAlgorithmParms: return -67771 case InvalidAttributeLabel: return -67772 case MissingAttributeLabel: return -67773 case InvalidAttributeKeyType: return -67774 case MissingAttributeKeyType: return -67775 case InvalidAttributeMode: return -67776 case MissingAttributeMode: return -67777 case InvalidAttributeEffectiveBits: return -67778 case MissingAttributeEffectiveBits: return -67779 case InvalidAttributeStartDate: return -67780 case MissingAttributeStartDate: return -67781 case InvalidAttributeEndDate: return -67782 case MissingAttributeEndDate: return -67783 case InvalidAttributeVersion: return -67784 case MissingAttributeVersion: return -67785 case InvalidAttributePrime: return -67786 case MissingAttributePrime: return -67787 case InvalidAttributeBase: return -67788 case MissingAttributeBase: return -67789 case InvalidAttributeSubprime: return -67790 case MissingAttributeSubprime: return -67791 case InvalidAttributeIterationCount: return -67792 case MissingAttributeIterationCount: return -67793 case InvalidAttributeDLDBHandle: return -67794 case MissingAttributeDLDBHandle: return -67795 case InvalidAttributeAccessCredentials: return -67796 case MissingAttributeAccessCredentials: return -67797 case InvalidAttributePublicKeyFormat: return -67798 case MissingAttributePublicKeyFormat: return -67799 case InvalidAttributePrivateKeyFormat: return -67800 case MissingAttributePrivateKeyFormat: return -67801 case InvalidAttributeSymmetricKeyFormat: return -67802 case MissingAttributeSymmetricKeyFormat: return -67803 case InvalidAttributeWrappedKeyFormat: return -67804 case MissingAttributeWrappedKeyFormat: return -67805 case StagedOperationInProgress: return -67806 case StagedOperationNotStarted: return -67807 case VerifyFailed: return -67808 case QuerySizeUnknown: return -67809 case BlockSizeMismatch: return -67810 case PublicKeyInconsistent: return -67811 case DeviceVerifyFailed: return -67812 case InvalidLoginName: return -67813 case AlreadyLoggedIn: return -67814 case InvalidDigestAlgorithm: return -67815 case InvalidCRLGroup: return -67816 case CertificateCannotOperate: return -67817 case CertificateExpired: return -67818 case CertificateNotValidYet: return -67819 case CertificateRevoked: return -67820 case CertificateSuspended: return -67821 case InsufficientCredentials: return -67822 case InvalidAction: return -67823 case InvalidAuthority: return -67824 case VerifyActionFailed: return -67825 case InvalidCertAuthority: return -67826 case InvaldCRLAuthority: return -67827 case InvalidCRLEncoding: return -67828 case InvalidCRLType: return -67829 case InvalidCRL: return -67830 case InvalidFormType: return -67831 case InvalidID: return -67832 case InvalidIdentifier: return -67833 case InvalidIndex: return -67834 case InvalidPolicyIdentifiers: return -67835 case InvalidTimeString: return -67836 case InvalidReason: return -67837 case InvalidRequestInputs: return -67838 case InvalidResponseVector: return -67839 case InvalidStopOnPolicy: return -67840 case InvalidTuple: return -67841 case MultipleValuesUnsupported: return -67842 case NotTrusted: return -67843 case NoDefaultAuthority: return -67844 case RejectedForm: return -67845 case RequestLost: return -67846 case RequestRejected: return -67847 case UnsupportedAddressType: return -67848 case UnsupportedService: return -67849 case InvalidTupleGroup: return -67850 case InvalidBaseACLs: return -67851 case InvalidTupleCredendtials: return -67852 case InvalidEncoding: return -67853 case InvalidValidityPeriod: return -67854 case InvalidRequestor: return -67855 case RequestDescriptor: return -67856 case InvalidBundleInfo: return -67857 case InvalidCRLIndex: return -67858 case NoFieldValues: return -67859 case UnsupportedFieldFormat: return -67860 case UnsupportedIndexInfo: return -67861 case UnsupportedLocality: return -67862 case UnsupportedNumAttributes: return -67863 case UnsupportedNumIndexes: return -67864 case UnsupportedNumRecordTypes: return -67865 case FieldSpecifiedMultiple: return -67866 case IncompatibleFieldFormat: return -67867 case InvalidParsingModule: return -67868 case DatabaseLocked: return -67869 case DatastoreIsOpen: return -67870 case MissingValue: return -67871 case UnsupportedQueryLimits: return -67872 case UnsupportedNumSelectionPreds: return -67873 case UnsupportedOperator: return -67874 case InvalidDBLocation: return -67875 case InvalidAccessRequest: return -67876 case InvalidIndexInfo: return -67877 case InvalidNewOwner: return -67878 case InvalidModifyMode: return -67879 default: return -99999 } } public var description : String { switch self { case Success: return "No error." case Unimplemented: return "Function or operation not implemented." case Param: return "One or more parameters passed to a function were not valid." case Allocate: return "Failed to allocate memory." case NotAvailable: return "No keychain is available. You may need to restart your computer." case ReadOnly: return "This keychain cannot be modified." case AuthFailed: return "The user name or passphrase you entered is not correct." case NoSuchKeychain: return "The specified keychain could not be found." case InvalidKeychain: return "The specified keychain is not a valid keychain file." case DuplicateKeychain: return "A keychain with the same name already exists." case DuplicateCallback: return "The specified callback function is already installed." case InvalidCallback: return "The specified callback function is not valid." case DuplicateItem: return "The specified item already exists in the keychain." case ItemNotFound: return "The specified item could not be found in the keychain." case BufferTooSmall: return "There is not enough memory available to use the specified item." case DataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case NoSuchAttr: return "The specified attribute does not exist." case InvalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case InvalidSearchRef: return "Unable to search the current keychain." case NoSuchClass: return "The specified item does not appear to be a valid keychain item." case NoDefaultKeychain: return "A default keychain could not be found." case InteractionNotAllowed: return "User interaction is not allowed." case ReadOnlyAttr: return "The specified attribute could not be modified." case WrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case KeySizeNotAllowed: return "This item specifies a key size which is too large." case NoStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case NoCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case NoPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case InteractionRequired: return "User interaction is required, but is currently not allowed." case DataNotAvailable: return "The contents of this item cannot be retrieved." case DataNotModifiable: return "The contents of this item cannot be modified." case CreateChainFailed: return "One or more certificates required to validate this certificate cannot be found." case InvalidPrefsDomain: return "The specified preferences domain is not valid." case ACLNotSimple: return "The specified access control list is not in standard (simple) form." case PolicyNotFound: return "The specified policy cannot be found." case InvalidTrustSetting: return "The specified trust setting is invalid." case NoAccessForItem: return "The specified item has no access control." case InvalidOwnerEdit: return "Invalid attempt to change the owner of this item." case TrustNotAvailable: return "No trust results are available." case UnsupportedFormat: return "Import/Export format unsupported." case UnknownFormat: return "Unknown format in import." case KeyIsSensitive: return "Key material must be wrapped for export." case MultiplePrivKeys: return "An attempt was made to import multiple private keys." case PassphraseRequired: return "Passphrase is required for import/export." case InvalidPasswordRef: return "The password reference was invalid." case InvalidTrustSettings: return "The Trust Settings Record was corrupted." case NoTrustSettings: return "No Trust Settings were found." case Pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case InvalidCertificate: return "This certificate could not be decoded." case NotSigner: return "A certificate was not signed by its proposed parent." case PolicyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case InvalidKey: return "The provided key material was not valid." case Decode: return "Unable to decode the provided data." case Internal: return "An internal error occured in the Security framework." case UnsupportedAlgorithm: return "An unsupported algorithm was encountered." case UnsupportedOperation: return "The operation you requested is not supported by this key." case UnsupportedPadding: return "The padding you requested is not supported." case ItemInvalidKey: return "A string key in dictionary is not one of the supported keys." case ItemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case ItemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case ItemClassMissing: return "No kSecItemClass key was specified in a dictionary." case ItemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case UseItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case UseKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case UseKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case ReturnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case ReturnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case ReturnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case ReturnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case ValueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case ValuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case ReturnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case MatchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case ItemIllegalQuery: return "The caller passed in a query which contained too many keys." case WaitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case MissingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case UpgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case MPSignatureInvalid: return "Signature invalid on MP message" case OTRTooOld: return "Message is too old to use" case OTRIDTooNew: return "Key ID is too new to use! Message from the future?" case ServiceNotAvailable: return "The required service is not available." case InsufficientClientID: return "The client ID is not correct." case DeviceReset: return "A device reset has occurred." case DeviceFailed: return "A device failure has occurred." case AppleAddAppACLSubject: return "Adding an application ACL subject failed." case ApplePublicKeyIncomplete: return "The public key is incomplete." case AppleSignatureMismatch: return "A signature mismatch has occurred." case AppleInvalidKeyStartDate: return "The specified key has an invalid start date." case AppleInvalidKeyEndDate: return "The specified key has an invalid end date." case ConversionError: return "A conversion error has occurred." case AppleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case DiskFull: return "The disk is full." case QuotaExceeded: return "The quota was exceeded." case FileTooBig: return "The file is too big." case InvalidDatabaseBlob: return "The specified database has an invalid blob." case InvalidKeyBlob: return "The specified database has an invalid key blob." case IncompatibleDatabaseBlob: return "The specified database has an incompatible blob." case IncompatibleKeyBlob: return "The specified database has an incompatible key blob." case HostNameMismatch: return "A host name mismatch has occurred." case UnknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case NoBasicConstraints: return "No basic constraints were found." case NoBasicConstraintsCA: return "No basic CA constraints were found." case InvalidAuthorityKeyID: return "The authority key ID is not valid." case InvalidSubjectKeyID: return "The subject key ID is not valid." case InvalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case InvalidExtendedKeyUsage: return "The extended key usage is not valid." case InvalidIDLinkage: return "The ID linkage is not valid." case PathLengthConstraintExceeded: return "The path length constraint was exceeded." case InvalidRoot: return "The root or anchor certificate is not valid." case CRLExpired: return "The CRL has expired." case CRLNotValidYet: return "The CRL is not yet valid." case CRLNotFound: return "The CRL was not found." case CRLServerDown: return "The CRL server is down." case CRLBadURI: return "The CRL has a bad Uniform Resource Identifier." case UnknownCertExtension: return "An unknown certificate extension was encountered." case UnknownCRLExtension: return "An unknown CRL extension was encountered." case CRLNotTrusted: return "The CRL is not trusted." case CRLPolicyFailed: return "The CRL policy failed." case IDPFailure: return "The issuing distribution point was not valid." case SMIMEEmailAddressesNotFound: return "An email address mismatch was encountered." case SMIMEBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case SMIMEBadKeyUsage: return "The key usage is not compatible with SMIME." case SMIMEKeyUsageNotCritical: return "The key usage extension is not marked as critical." case SMIMENoEmailAddress: return "No email address was found in the certificate." case SMIMESubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case SSLBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case OCSPBadResponse: return "The OCSP response was incorrect or could not be parsed." case OCSPBadRequest: return "The OCSP request was incorrect or could not be parsed." case OCSPUnavailable: return "OCSP service is unavailable." case OCSPStatusUnrecognized: return "The OCSP server did not recognize this certificate." case EndOfData: return "An end-of-data was detected." case IncompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case NetworkFailure: return "A network failure occurred." case OCSPNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case RecordModified: return "The record was modified." case OCSPSignatureError: return "The OCSP response had an invalid signature." case OCSPNoSigner: return "The OCSP response had no signer." case OCSPResponderMalformedReq: return "The OCSP responder was given a malformed request." case OCSPResponderInternalError: return "The OCSP responder encountered an internal error." case OCSPResponderTryLater: return "The OCSP responder is busy, try again later." case OCSPResponderSignatureRequired: return "The OCSP responder requires a signature." case OCSPResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case OCSPResponseNonceMismatch: return "The OCSP response nonce did not match the request." case CodeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case CodeSigningNoBasicConstraints: return "Code signing found no basic constraints." case CodeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case CodeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case CodeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case ResourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case ResourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case TrustSettingDeny: return "The trust setting for this policy was set to Deny." case InvalidSubjectName: return "An invalid certificate subject name was encountered." case UnknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case MobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case MobileMeRequestRedirected: return "The MobileMe request was redirected." case MobileMeServerError: return "A MobileMe server error occurred." case MobileMeServerNotAvailable: return "The MobileMe server is not available." case MobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case MobileMeServerServiceErr: return "A MobileMe service error has occurred." case MobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case MobileMeNoRequestPending: return "MobileMe has no request pending." case MobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case MobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case NotInitialized: return "A function was called without initializing CSSM." case InvalidHandleUsage: return "The CSSM handle does not match with the service type." case PVCReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case FunctionIntegrityFail: return "A function address was not within the verified module." case InternalError: return "An internal error has occurred." case MemoryError: return "A memory error has occurred." case InvalidData: return "Invalid data was encountered." case MDSError: return "A Module Directory Service error has occurred." case InvalidPointer: return "An invalid pointer was encountered." case SelfCheckFailed: return "Self-check has failed." case FunctionFailed: return "A function has failed." case ModuleManifestVerifyFailed: return "A module manifest verification failure has occurred." case InvalidGUID: return "An invalid GUID was encountered." case InvalidHandle: return "An invalid handle was encountered." case InvalidDBList: return "An invalid DB list was encountered." case InvalidPassthroughID: return "An invalid passthrough ID was encountered." case InvalidNetworkAddress: return "An invalid network address was encountered." case CRLAlreadySigned: return "The certificate revocation list is already signed." case InvalidNumberOfFields: return "An invalid number of fields were encountered." case VerificationFailure: return "A verification failure occurred." case UnknownTag: return "An unknown tag was encountered." case InvalidSignature: return "An invalid signature was encountered." case InvalidName: return "An invalid name was encountered." case InvalidCertificateRef: return "An invalid certificate reference was encountered." case InvalidCertificateGroup: return "An invalid certificate group was encountered." case TagNotFound: return "The specified tag was not found." case InvalidQuery: return "The specified query was not valid." case InvalidValue: return "An invalid value was detected." case CallbackFailed: return "A callback has failed." case ACLDeleteFailed: return "An ACL delete operation has failed." case ACLReplaceFailed: return "An ACL replace operation has failed." case ACLAddFailed: return "An ACL add operation has failed." case ACLChangeFailed: return "An ACL change operation has failed." case InvalidAccessCredentials: return "Invalid access credentials were encountered." case InvalidRecord: return "An invalid record was encountered." case InvalidACL: return "An invalid ACL was encountered." case InvalidSampleValue: return "An invalid sample value was encountered." case IncompatibleVersion: return "An incompatible version was encountered." case PrivilegeNotGranted: return "The privilege was not granted." case InvalidScope: return "An invalid scope was encountered." case PVCAlreadyConfigured: return "The PVC is already configured." case InvalidPVC: return "An invalid PVC was encountered." case EMMLoadFailed: return "The EMM load has failed." case EMMUnloadFailed: return "The EMM unload has failed." case AddinLoadFailed: return "The add-in load operation has failed." case InvalidKeyRef: return "An invalid key was encountered." case InvalidKeyHierarchy: return "An invalid key hierarchy was encountered." case AddinUnloadFailed: return "The add-in unload operation has failed." case LibraryReferenceNotFound: return "A library reference was not found." case InvalidAddinFunctionTable: return "An invalid add-in function table was encountered." case InvalidServiceMask: return "An invalid service mask was encountered." case ModuleNotLoaded: return "A module was not loaded." case InvalidSubServiceID: return "An invalid subservice ID was encountered." case AttributeNotInContext: return "An attribute was not in the context." case ModuleManagerInitializeFailed: return "A module failed to initialize." case ModuleManagerNotFound: return "A module was not found." case EventNotificationCallbackNotFound: return "An event notification callback was not found." case InputLengthError: return "An input length error was encountered." case OutputLengthError: return "An output length error was encountered." case PrivilegeNotSupported: return "The privilege is not supported." case DeviceError: return "A device error was encountered." case AttachHandleBusy: return "The CSP handle was busy." case NotLoggedIn: return "You are not logged in." case AlgorithmMismatch: return "An algorithm mismatch was encountered." case KeyUsageIncorrect: return "The key usage is incorrect." case KeyBlobTypeIncorrect: return "The key blob type is incorrect." case KeyHeaderInconsistent: return "The key header is inconsistent." case UnsupportedKeyFormat: return "The key header format is not supported." case UnsupportedKeySize: return "The key size is not supported." case InvalidKeyUsageMask: return "The key usage mask is not valid." case UnsupportedKeyUsageMask: return "The key usage mask is not supported." case InvalidKeyAttributeMask: return "The key attribute mask is not valid." case UnsupportedKeyAttributeMask: return "The key attribute mask is not supported." case InvalidKeyLabel: return "The key label is not valid." case UnsupportedKeyLabel: return "The key label is not supported." case InvalidKeyFormat: return "The key format is not valid." case UnsupportedVectorOfBuffers: return "The vector of buffers is not supported." case InvalidInputVector: return "The input vector is not valid." case InvalidOutputVector: return "The output vector is not valid." case InvalidContext: return "An invalid context was encountered." case InvalidAlgorithm: return "An invalid algorithm was encountered." case InvalidAttributeKey: return "A key attribute was not valid." case MissingAttributeKey: return "A key attribute was missing." case InvalidAttributeInitVector: return "An init vector attribute was not valid." case MissingAttributeInitVector: return "An init vector attribute was missing." case InvalidAttributeSalt: return "A salt attribute was not valid." case MissingAttributeSalt: return "A salt attribute was missing." case InvalidAttributePadding: return "A padding attribute was not valid." case MissingAttributePadding: return "A padding attribute was missing." case InvalidAttributeRandom: return "A random number attribute was not valid." case MissingAttributeRandom: return "A random number attribute was missing." case InvalidAttributeSeed: return "A seed attribute was not valid." case MissingAttributeSeed: return "A seed attribute was missing." case InvalidAttributePassphrase: return "A passphrase attribute was not valid." case MissingAttributePassphrase: return "A passphrase attribute was missing." case InvalidAttributeKeyLength: return "A key length attribute was not valid." case MissingAttributeKeyLength: return "A key length attribute was missing." case InvalidAttributeBlockSize: return "A block size attribute was not valid." case MissingAttributeBlockSize: return "A block size attribute was missing." case InvalidAttributeOutputSize: return "An output size attribute was not valid." case MissingAttributeOutputSize: return "An output size attribute was missing." case InvalidAttributeRounds: return "The number of rounds attribute was not valid." case MissingAttributeRounds: return "The number of rounds attribute was missing." case InvalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case MissingAlgorithmParms: return "An algorithm parameters attribute was missing." case InvalidAttributeLabel: return "A label attribute was not valid." case MissingAttributeLabel: return "A label attribute was missing." case InvalidAttributeKeyType: return "A key type attribute was not valid." case MissingAttributeKeyType: return "A key type attribute was missing." case InvalidAttributeMode: return "A mode attribute was not valid." case MissingAttributeMode: return "A mode attribute was missing." case InvalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case MissingAttributeEffectiveBits: return "An effective bits attribute was missing." case InvalidAttributeStartDate: return "A start date attribute was not valid." case MissingAttributeStartDate: return "A start date attribute was missing." case InvalidAttributeEndDate: return "An end date attribute was not valid." case MissingAttributeEndDate: return "An end date attribute was missing." case InvalidAttributeVersion: return "A version attribute was not valid." case MissingAttributeVersion: return "A version attribute was missing." case InvalidAttributePrime: return "A prime attribute was not valid." case MissingAttributePrime: return "A prime attribute was missing." case InvalidAttributeBase: return "A base attribute was not valid." case MissingAttributeBase: return "A base attribute was missing." case InvalidAttributeSubprime: return "A subprime attribute was not valid." case MissingAttributeSubprime: return "A subprime attribute was missing." case InvalidAttributeIterationCount: return "An iteration count attribute was not valid." case MissingAttributeIterationCount: return "An iteration count attribute was missing." case InvalidAttributeDLDBHandle: return "A database handle attribute was not valid." case MissingAttributeDLDBHandle: return "A database handle attribute was missing." case InvalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case MissingAttributeAccessCredentials: return "An access credentials attribute was missing." case InvalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case MissingAttributePublicKeyFormat: return "A public key format attribute was missing." case InvalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case MissingAttributePrivateKeyFormat: return "A private key format attribute was missing." case InvalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case MissingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case InvalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case MissingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case StagedOperationInProgress: return "A staged operation is in progress." case StagedOperationNotStarted: return "A staged operation was not started." case VerifyFailed: return "A cryptographic verification failure has occurred." case QuerySizeUnknown: return "The query size is unknown." case BlockSizeMismatch: return "A block size mismatch occurred." case PublicKeyInconsistent: return "The public key was inconsistent." case DeviceVerifyFailed: return "A device verification failure has occurred." case InvalidLoginName: return "An invalid login name was detected." case AlreadyLoggedIn: return "The user is already logged in." case InvalidDigestAlgorithm: return "An invalid digest algorithm was detected." case InvalidCRLGroup: return "An invalid CRL group was detected." case CertificateCannotOperate: return "The certificate cannot operate." case CertificateExpired: return "An expired certificate was detected." case CertificateNotValidYet: return "The certificate is not yet valid." case CertificateRevoked: return "The certificate was revoked." case CertificateSuspended: return "The certificate was suspended." case InsufficientCredentials: return "Insufficient credentials were detected." case InvalidAction: return "The action was not valid." case InvalidAuthority: return "The authority was not valid." case VerifyActionFailed: return "A verify action has failed." case InvalidCertAuthority: return "The certificate authority was not valid." case InvaldCRLAuthority: return "The CRL authority was not valid." case InvalidCRLEncoding: return "The CRL encoding was not valid." case InvalidCRLType: return "The CRL type was not valid." case InvalidCRL: return "The CRL was not valid." case InvalidFormType: return "The form type was not valid." case InvalidID: return "The ID was not valid." case InvalidIdentifier: return "The identifier was not valid." case InvalidIndex: return "The index was not valid." case InvalidPolicyIdentifiers: return "The policy identifiers are not valid." case InvalidTimeString: return "The time specified was not valid." case InvalidReason: return "The trust policy reason was not valid." case InvalidRequestInputs: return "The request inputs are not valid." case InvalidResponseVector: return "The response vector was not valid." case InvalidStopOnPolicy: return "The stop-on policy was not valid." case InvalidTuple: return "The tuple was not valid." case MultipleValuesUnsupported: return "Multiple values are not supported." case NotTrusted: return "The trust policy was not trusted." case NoDefaultAuthority: return "No default authority was detected." case RejectedForm: return "The trust policy had a rejected form." case RequestLost: return "The request was lost." case RequestRejected: return "The request was rejected." case UnsupportedAddressType: return "The address type is not supported." case UnsupportedService: return "The service is not supported." case InvalidTupleGroup: return "The tuple group was not valid." case InvalidBaseACLs: return "The base ACLs are not valid." case InvalidTupleCredendtials: return "The tuple credentials are not valid." case InvalidEncoding: return "The encoding was not valid." case InvalidValidityPeriod: return "The validity period was not valid." case InvalidRequestor: return "The requestor was not valid." case RequestDescriptor: return "The request descriptor was not valid." case InvalidBundleInfo: return "The bundle information was not valid." case InvalidCRLIndex: return "The CRL index was not valid." case NoFieldValues: return "No field values were detected." case UnsupportedFieldFormat: return "The field format is not supported." case UnsupportedIndexInfo: return "The index information is not supported." case UnsupportedLocality: return "The locality is not supported." case UnsupportedNumAttributes: return "The number of attributes is not supported." case UnsupportedNumIndexes: return "The number of indexes is not supported." case UnsupportedNumRecordTypes: return "The number of record types is not supported." case FieldSpecifiedMultiple: return "Too many fields were specified." case IncompatibleFieldFormat: return "The field format was incompatible." case InvalidParsingModule: return "The parsing module was not valid." case DatabaseLocked: return "The database is locked." case DatastoreIsOpen: return "The data store is open." case MissingValue: return "A missing value was detected." case UnsupportedQueryLimits: return "The query limits are not supported." case UnsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case UnsupportedOperator: return "The operator is not supported." case InvalidDBLocation: return "The database location is not valid." case InvalidAccessRequest: return "The access request is not valid." case InvalidIndexInfo: return "The index information is not valid." case InvalidNewOwner: return "The new owner is not valid." case InvalidModifyMode: return "The modify mode is not valid." default: return "Unexpected error has occurred." } } }
mit
M2Mobi/Marky-Mark
Package.swift
1
445
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "Marky-Mark", platforms: [ .iOS("8.0"), ], products: [ .library( name: "markymark", targets: ["markymark"]), ], dependencies: [], targets: [ .target( name: "markymark", dependencies: [], path: "markymark"), ], swiftLanguageVersions: [.v5] )
mit
SeriousChoice/SCSwift
SCSwift/Form/SCAttachmentTableCell.swift
1
3539
// // SCAttachmentTableCell.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit class SCAttachmentTableCell: UITableViewCell { public var lblTitle: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() public var imgAttachment: UIImageView = { let image = UIImageView() image.layer.cornerRadius = 3 image.clipsToBounds = true return image }() public var lblFileName: UILabel = { let label = UILabel() label.numberOfLines = 1 return label }() public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) clipsToBounds = true accessoryType = .disclosureIndicator setupLayout() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } private func setupLayout() { let margin = SCFormViewController.cellsMargin contentView.addSubview(lblTitle) lblTitle.sc_pinEdge(toSuperViewEdge: .top, withOffset: margin) lblTitle.sc_pinEdge(toSuperViewEdge: .leading, withOffset: 20) lblTitle.sc_pinEdge(toSuperViewEdge: .bottom, withOffset: -margin) lblTitle.setContentHuggingPriority(.defaultHigh, for: .horizontal) lblTitle.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) contentView.addSubview(imgAttachment) imgAttachment.sc_setDimension(.width, withValue: 30) imgAttachment.sc_setDimension(.height, withValue: 30) imgAttachment.sc_pinEdge(toSuperViewEdge: .trailing, withOffset: -40) imgAttachment.sc_alignAxis(axis: .vertical, toView: lblTitle) contentView.addSubview(lblFileName) lblFileName.sc_pinEdge(toSuperViewEdge: .top, withOffset: margin) lblFileName.sc_pinEdge(toSuperViewEdge: .trailing, withOffset: -40) lblFileName.sc_pinEdge(toSuperViewEdge: .bottom, withOffset: -margin) lblFileName.setContentHuggingPriority(.defaultLow, for: .horizontal) lblFileName.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) lblTitle.sc_pinEdge(.trailing, toEdge: .leading, ofView: imgAttachment, withOffset: 20, withRelation: .greaterOrEqual) lblTitle.sc_pinEdge(.trailing, toEdge: .leading, ofView: lblFileName, withOffset: -20, withRelation: .greaterOrEqual) } public override func configure(with row: SCFormRow) { lblTitle.text = row.mandatory ? "\(row.title ?? "")*" : row.title if let url = row.attachmentUrl { if let image = UIImage(contentsOfFile: url.absoluteString.replacingOccurrences(of: "file://", with: "")) { imgAttachment.image = image lblFileName.text = nil } else { imgAttachment.image = nil lblFileName.text = url.lastPathComponent } } else { imgAttachment.image = nil lblFileName.text = nil } } }
mit
Automattic/Automattic-Tracks-iOS
Tests/Tests/TracksEventPersistenceServiceTests.swift
1
7342
@testable import AutomatticTracks import XCTest import SwiftUI class TracksEventPersistenceServiceTests: XCTestCase { // MARK: - Helper methods func createTestTracksEvent(_ uuid: UUID) -> TracksEvent { let event = TracksEvent() event.uuid = uuid event.eventName = "test_event_name" event.date = Date() event.username = "AnonymousTestUser" event.userID = "AnonymousTestUser" event.userAgent = "TestUserAgent" event.userType = .anonymous return event } func createTracksEvents(uuids: [UUID]) -> [TracksEvent] { uuids.map { uuid in createTestTracksEvent(uuid) } } func fetchTrackEventCoreData(for uuids: [UUID], context: NSManagedObjectContext, andDo completion: @escaping (Result<[TracksEventCoreData], Error>) -> Void) { let uuidStrings = uuids.map { $0.uuidString } context.performAndWait { let fetchRequest = NSFetchRequest<TracksEventCoreData>(entityName: "TracksEvent") fetchRequest.predicate = NSPredicate(format: "uuid in %@", uuidStrings) do { let events = try fetchRequest.execute() completion(.success(events)) } catch { completion(.failure(error)) } } } // MARK: - Tests /// Tests that persisting a tracks event works. /// func testPersistTracksEvent() { let contextManager = TracksTestContextManager() let context = contextManager.managedObjectContext let service = TracksEventPersistenceService(managedObjectContext: context) let uuid = UUID() let event = createTestTracksEvent(uuid) XCTAssertNoThrow(try event.validateObject()) service.persistTracksEvent(event) context.performAndWait { let fetchRequest = NSFetchRequest<TracksEventCoreData>(entityName: "TracksEvent") fetchRequest.predicate = NSPredicate(format: "uuid = %@", uuid.uuidString) do { let result = try fetchRequest.execute() XCTAssertEqual(result.count, 1) } catch { XCTFail() } } } func testIncrementRetryCount() { let testCompletedExpectation = expectation(description: "The test is run completely") testCompletedExpectation.expectedFulfillmentCount = 1 testCompletedExpectation.assertForOverFulfill = true let contextManager = TracksTestContextManager() let context = contextManager.managedObjectContext let service = TracksEventPersistenceService(managedObjectContext: context) let uuids = (0 ..< 2002).map { index in UUID() } let tracksEvents = createTracksEvents(uuids: uuids) XCTAssertEqual(tracksEvents.count, uuids.count) for event in tracksEvents { service.persistTracksEvent(event) } // We're adding an extra event that should not have its retry count incremented. let extraUUID = UUID() service.persistTracksEvent(createTestTracksEvent(extraUUID)) // The first control includes the extra UUID because all retry counts should be zero fetchTrackEventCoreData(for: uuids + [extraUUID], context: context) { result in switch result { case .success(let events): XCTAssertEqual(tracksEvents.count + 1, events.count) // +1 for the extra event for event in events { XCTAssertEqual(event.retryCount, 0) } case .failure(let error): XCTFail("Error: \(String(describing: error))") } } service.incrementRetryCount(forEvents: tracksEvents) { [unowned self] in self.fetchTrackEventCoreData(for: uuids, context: context) { result in switch result { case .success(let events): XCTAssertEqual(tracksEvents.count, events.count) for event in events { XCTAssertEqual(event.retryCount, 1) } case .failure(let error): XCTFail("Error: \(String(describing: error))") } } // Make sure our extra UUID's retry count hasn't changed self.fetchTrackEventCoreData(for: [extraUUID], context: context) { result in switch result { case .success(let events): XCTAssertEqual(1, events.count) for event in events { XCTAssertEqual(event.retryCount, 0) } testCompletedExpectation.fulfill() case .failure(let error): XCTFail("Error: \(String(describing: error))") } } } waitForExpectations(timeout: 1) } /// This is a bit of a strange test because: /// 1. Events should not be missing from the persistance layer; and /// 2. Event missing from the persistance layer are no-ops in terms of increasing the retry count. /// /// But the reason this test can be good is because it documents and sets the expectation on what happens /// when some of the events are not in the persistance layer, and some are - the expected behaviour is that /// those that are present should still have their retry count increased, while those missing should be treated /// as logged errors without affecting the overall process. /// /// This test actually made me spot and fix a few important bugs in the code. /// func testIncrementRetryCountForEventsNotPersisted() { let testCompletedExpectation = expectation(description: "The test is run completely") testCompletedExpectation.expectedFulfillmentCount = 1 testCompletedExpectation.assertForOverFulfill = true let contextManager = TracksTestContextManager() let context = contextManager.managedObjectContext let service = TracksEventPersistenceService(managedObjectContext: context) let uuids = (0 ..< 2002).map { index in UUID() } let tracksEvents = createTracksEvents(uuids: uuids) XCTAssertEqual(tracksEvents.count, uuids.count) // We're adding an extra event that should have its retry count incremented // since its the only one persisted. let extraUUID = UUID() let extraEvent = createTestTracksEvent(extraUUID) service.persistTracksEvent(extraEvent) service.incrementRetryCount(forEvents: tracksEvents + [extraEvent]) { self.fetchTrackEventCoreData(for: uuids + [extraUUID], context: context) { result in switch result { case .success(let events): XCTAssertEqual(1, events.count) for event in events { XCTAssertEqual(event.retryCount, 1) } testCompletedExpectation.fulfill() case .failure(let error): XCTFail("Error: \(String(describing: error))") } } } waitForExpectations(timeout: 1) } }
gpl-2.0
mattermost/mattermost-mobile
ios/MattermostShare/Views/ErrorViews/NoServersView.swift
1
667
// // NoServersView.swift // MattermostShare // // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // import SwiftUI struct NoServersView: View { var body: some View { VStack (spacing: 8) { Text("Not connected to any servers") .font(Font.custom("Metropolis-SemiBold", size: 20)) .foregroundColor(Color.theme.centerChannelColor) Text("To share content, you'll need to be logged in to a Mattermost server.") .font(Font.custom("OpenSans", size: 16)) .foregroundColor(Color.theme.centerChannelColor.opacity(0.72)) } .padding(.horizontal, 12) } }
apache-2.0
michaello/Aloha
AlohaGIF/ImagePicker/ImageGallery/ImageGalleryView.swift
1
8360
import UIKit import Photos fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } protocol ImageGalleryPanGestureDelegate: class { func panGestureDidStart() func panGestureDidChange(_ translation: CGPoint) func panGestureDidEnd(_ translation: CGPoint, velocity: CGPoint) func tooLongMovieSelected() } open class ImageGalleryView: UIView { struct Dimensions { static let galleryHeight: CGFloat = 160 static let galleryBarHeight: CGFloat = 24 } var configuration = Configuration() lazy open var collectionView: UICollectionView = { [unowned self] in let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = self.configuration.mainColor collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self return collectionView }() lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in let layout = ImageGalleryLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = self.configuration.cellSpacing layout.minimumLineSpacing = 2 layout.sectionInset = UIEdgeInsets.zero return layout }() lazy var topSeparator: UIView = { [unowned self] in let view = UIView() view.isHidden = true view.translatesAutoresizingMaskIntoConstraints = false view.addGestureRecognizer(self.panGestureRecognizer) view.backgroundColor = self.configuration.gallerySeparatorColor return view }() lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in let gesture = UIPanGestureRecognizer() gesture.addTarget(self, action: #selector(handlePanGestureRecognizer(_:))) return gesture }() open lazy var noImagesLabel: UILabel = { [unowned self] in let label = UILabel() label.isHidden = true label.font = self.configuration.noImagesFont label.textColor = self.configuration.noImagesColor label.text = self.configuration.noImagesTitle label.alpha = 0 label.sizeToFit() self.addSubview(label) return label }() open lazy var selectedStack = ImageStack() lazy var assets = [PHAsset]() weak var delegate: ImageGalleryPanGestureDelegate? var collectionSize: CGSize? var shouldTransform = false var imagesBeforeLoading = 0 var fetchResult: PHFetchResult<AnyObject>? var imageLimit = 0 // MARK: - Initializers public init(configuration: Configuration? = nil) { if let configuration = configuration { self.configuration = configuration } super.init(frame: .zero) configure() } override init(frame: CGRect) { super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { backgroundColor = configuration.mainColor collectionView.register(ImageGalleryViewCell.self, forCellWithReuseIdentifier: CollectionView.reusableIdentifier) [collectionView, topSeparator].forEach { addSubview($0) } topSeparator.addSubview(configuration.indicatorView) imagesBeforeLoading = 0 fetchPhotos() } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() updateNoImagesLabel() } func updateFrames() { let totalWidth = UIScreen.main.bounds.width frame.size.width = totalWidth let collectionFrame = frame.height == Dimensions.galleryBarHeight ? 100 + Dimensions.galleryBarHeight : frame.height topSeparator.frame = CGRect(x: 0, y: 0, width: totalWidth, height: Dimensions.galleryBarHeight) topSeparator.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] configuration.indicatorView.frame = CGRect(x: (totalWidth - configuration.indicatorWidth) / 2, y: (topSeparator.frame.height - configuration.indicatorHeight) / 2, width: configuration.indicatorWidth, height: configuration.indicatorHeight) collectionView.frame = CGRect(x: 0, y: 0, width: totalWidth, height: collectionFrame) collectionSize = CGSize(width: collectionView.frame.height, height: collectionView.frame.height) collectionView.reloadData() } func updateNoImagesLabel() { let height = bounds.height let threshold = Dimensions.galleryBarHeight * 2 UIView.animate(withDuration: 0.25, animations: { if threshold > height || self.collectionView.alpha != 0 { self.noImagesLabel.alpha = 0 } else { self.noImagesLabel.center = CGPoint(x: self.bounds.width / 2, y: height / 2) self.noImagesLabel.alpha = (height > threshold) ? 1 : (height - Dimensions.galleryBarHeight) / threshold } }) } // MARK: - Photos handler func fetchPhotos(_ completion: (() -> Void)? = nil) { AssetManager.fetch(withConfiguration: configuration) { assets in self.assets.removeAll() self.assets.append(contentsOf: assets) self.collectionView.reloadData() completion?() } } // MARK: - Pan gesture recognizer func handlePanGestureRecognizer(_ gesture: UIPanGestureRecognizer) { guard let superview = superview else { return } let translation = gesture.translation(in: superview) let velocity = gesture.velocity(in: superview) switch gesture.state { case .began: delegate?.panGestureDidStart() case .changed: delegate?.panGestureDidChange(translation) case .ended: delegate?.panGestureDidEnd(translation, velocity: velocity) default: break } } func displayNoImagesMessage(_ hideCollectionView: Bool) { collectionView.alpha = hideCollectionView ? 0 : 1 updateNoImagesLabel() } } // MARK: CollectionViewFlowLayout delegate methods extension ImageGalleryView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let collectionSize = collectionSize else { return CGSize.zero } return collectionSize } } // MARK: CollectionView delegate methods extension ImageGalleryView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ImageGalleryViewCell else { return } for asset in self.selectedStack.assets { self.selectedStack.dropAsset(asset) } // Animate deselecting photos for any selected visible cells guard let visibleCells = collectionView.visibleCells as? [ImageGalleryViewCell] else { return } for cell in visibleCells { if cell.selectedImageView.image != nil && cell.selectedImageView.image != AssetManager.getImage("infoIcon") { UIView.animate(withDuration: 0.2, animations: { cell.selectedImageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) }, completion: { _ in cell.selectedImageView.image = nil }) } } let asset = assets[(indexPath as NSIndexPath).row] AssetManager.selectedAsset = asset AssetManager.resolveAsset(asset, size: CGSize(width: 100, height: 100)) { image in guard let _ = image else { return } if cell.selectedImageView.image != nil { UIView.animate(withDuration: 0.2, animations: { cell.selectedImageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) }, completion: { _ in cell.selectedImageView.image = nil }) self.selectedStack.dropAsset(asset) } else if self.imageLimit == 0 || self.imageLimit > self.selectedStack.assets.count { cell.selectedImageView.image = AssetManager.getImage("selectedImageGallery") cell.selectedImageView.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: 0.2, animations: { _ in cell.selectedImageView.transform = CGAffineTransform.identity }) self.selectedStack.pushAsset(asset) } } } }
mit
eleks/rnd-nearables-wearables
iOS/BeaconMe/BeaconMe/Model/Favorites.swift
1
1792
// // Favorites.swift // BeaconMe // // Created by Bogdan Shubravyi on 7/27/15. // Copyright (c) 2015 Eleks. All rights reserved. // import UIKit class Favorites { private let favoritesKey = "Favorites" private var cache: Array<String> = [] private var queue = dispatch_queue_create("favoritesQueue", DISPATCH_QUEUE_CONCURRENT); init() { dispatch_barrier_sync(queue) { () in if let storedFavorites = NSUserDefaults.standardUserDefaults().objectForKey(self.favoritesKey) as? [String] { self.cache = storedFavorites } else { self.cache = [] } } } func clear() { dispatch_barrier_async(queue) { () in self.cache.removeAll(keepCapacity: false) self.saveFavorites() } } func getFavorites() -> [String] { var result: [String]! dispatch_sync(queue) { () in result = self.cache } return result } func addFavorite(favorite: String) { dispatch_barrier_async(queue) { () in if !contains(self.cache, favorite) { self.cache.append(favorite) self.saveFavorites() } } } func removeFavorite(favorite: String) { dispatch_barrier_async(queue) { () in if let index = find(self.cache, favorite) { self.cache.removeAtIndex(index) self.saveFavorites() } } } private func saveFavorites() { NSUserDefaults.standardUserDefaults().setObject(self.cache, forKey: self.favoritesKey) NSUserDefaults.standardUserDefaults().synchronize() } }
mit
wjk/SwiftXPC
SwiftXPC/Transport/Connection.swift
1
3458
// // Connection.swift // DOS Prompt // // Created by William Kent on 7/28/14. // Copyright (c) 2014 William Kent. All rights reserved. // import Foundation import dispatch import XPC public final class XPCConnection : XPCObject { public class func createAnonymousConnection() -> XPCConnection { return XPCConnection(nativePointer: xpc_connection_create(nil, nil)) } public convenience init(name: String) { self.init(name: name, queue: nil) } public convenience init(name: String, queue: dispatch_queue_t?) { let namePtr = name.cStringUsingEncoding(NSUTF8StringEncoding) self.init(nativePointer: xpc_connection_create(namePtr!, queue)) } public convenience init(endpoint: XPCEndpoint) { self.init(nativePointer: xpc_connection_create_from_endpoint(endpoint.objectPointer)) } public func setTargetQueue(queue: dispatch_queue_t?) { xpc_connection_set_target_queue(objectPointer, queue) } public func setHandler(block: (XPCObject) -> ()) { xpc_connection_set_event_handler(objectPointer) { ptr in block(XPCObject(nativePointer: ptr)) } } public func suspend() { xpc_connection_suspend(objectPointer) } public func resume() { xpc_connection_resume(objectPointer) } public func sendMessage(message: XPCDictionary) { xpc_connection_send_message(objectPointer, message.objectPointer) } public func sendMessage(message: XPCDictionary, replyHandler: (XPCObject) -> ()) { xpc_connection_send_message_with_reply(objectPointer, message.objectPointer, nil) { obj in replyHandler(XPCObject(nativePointer: obj)) } } public func sendBarrier(barrier: () -> ()) { xpc_connection_send_barrier(objectPointer) { barrier() } } public func cancel() { xpc_connection_cancel(objectPointer) } // MARK: Properties public var name: String? { get { let ptr = xpc_connection_get_name(objectPointer) if ptr != nil { return String.fromCString(ptr) } else { return nil } } } public var effectiveUserIdOfRemotePeer : Int { get { return Int(xpc_connection_get_euid(objectPointer)) } } public var effectiveGroupIdOfRemotePeer : Int { get { return Int(xpc_connection_get_egid(objectPointer)) } } public var processIdOfRemotePeer : Int { get { return Int(xpc_connection_get_pid(objectPointer)) } } public var auditSessionIdOfRemotePeer : Int { get { return Int(xpc_connection_get_asid(objectPointer)) } } } extension XPCDictionary { public var remoteConnection: XPCConnection { get { return XPCConnection(nativePointer: xpc_dictionary_get_remote_connection(objectPointer)) } } // Note: Due to the underlying implementation, this method will only work once. // Subsequent calls will return nil. In addition, if the receiver does not have // a reply context, this method will always return nil. public func createReply() -> XPCDictionary? { let ptr = xpc_dictionary_create_reply(objectPointer) if ptr == nil { return nil } return XPCDictionary(nativePointer: ptr) } }
mit
andrewgrant/Playgrounds
Variadic.playground/Contents.swift
1
492
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" func arrayVarAgs(args :[CVarArgType]) { let num = args.count print(String(format: "Vags1 got %d objects", num)) } func rawVarArgs(args : CVarArgType...) { let num = args.count print(String(format: "Vags2 got %d objects", num)) arrayVarAgs(args) } rawVarArgs("Hello", "one") var globalString = "Boo" //Logger.Instance.Cloudkit.info("Got to line %d", 7)
mit
Vadimkomis/Myclok
Pods/Auth0/Auth0/ResponseType.swift
2
2048
// ResponseType.swift // // Copyright (c) 2016 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// /// List of supported response_types /// ImplicitGrant /// [.token] /// [.idToken] /// [.token, .idToken] /// /// PKCE /// [.code] /// [.code, token] /// [.code, idToken] /// [.code, token, .idToken] /// public struct ResponseType: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let token = ResponseType(rawValue: 1 << 0) public static let idToken = ResponseType(rawValue: 1 << 1) public static let code = ResponseType(rawValue: 1 << 2) var label: String? { switch self.rawValue { case ResponseType.token.rawValue: return "token" case ResponseType.idToken.rawValue: return "id_token" case ResponseType.code.rawValue: return "code" default: return nil } } }
mit
fsproru/ScoutReport
ScoutReport/Presenter.swift
1
552
import UIKit protocol PresenterType { func present(underlyingViewController underlyingViewController: UIViewController, viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) } class Presenter: PresenterType { func present(underlyingViewController underlyingViewController: UIViewController, viewControllerToPresent: UIViewController, animated: Bool, completion: (() -> Void)?) { underlyingViewController.presentViewController(viewControllerToPresent, animated: animated, completion: completion) } }
mit
debugsquad/metalic
metalic/Model/Filters/Basic/MFiltersItemBasicGothic.swift
1
449
import Foundation class MFiltersItemBasicGothic:MFiltersItem { private let kImageName:String = "assetFilterGothic" private let kCommitable:Bool = true required init() { let name:String = NSLocalizedString("MFiltersItemBasicGothic_name", comment:"") let filter:MetalFilter.Type = MetalFilterBasicGothic.self super.init(name:name, asset:kImageName, filter:filter, commitable:kCommitable) } }
mit
austinzheng/swift-compiler-crashes
fixed/25382-swift-typechecker-overapproximateosversionsatlocation.swift
7
230
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a{var b{class A{var f=[0}}protocol A{}struct A{let a{A{
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/14222-swift-sourcemanager-getmessage.swift
11
249
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing ( { extension NSSet { { } protocol b { class A { struct B { init { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/17715-swift-sourcemanager-getmessage.swift
11
253
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum b { func c ( ) -> { protocol a { let start = [Void{ } { class A { class case ,
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/13190-swift-sourcemanager-getmessage.swift
11
255
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing extension String { var d = { protocol b { { } struct A { { } { } let a { class case ,
mit
kiliankoe/catchmybus
catchmybus/ConnectionManager.swift
1
3255
// // ConnectionManager.swift // catchmybus // // Created by Kilian Koeltzsch on 13/01/15. // Copyright (c) 2015 Kilian Koeltzsch. All rights reserved. // import Foundation import SwiftyJSON private let _ConnectionManagerSharedInstace = ConnectionManager() class ConnectionManager { // ConnectionManager is a singleton, accessible via ConnectionManager.shared() static func shared() -> ConnectionManager { return _ConnectionManagerSharedInstace } // MARK: - Properties internal var stopDict = [String: Int]() internal var notificationDict = [String: Int]() var connections = [Connection]() var selectedConnection: Connection? { get { return self.selectedConnection } set(newSelection) { self.deselectAll() newSelection!.selected = true self.selectedConnection = newSelection // is this needed? } } var selectedStop: String? // TODO: Should the ConnectionManager be keeping the list of stops as well? // MARK: - init () { loadDefaults() } /** Load internal stopDict, notificationDict and selectedStop from NSUserDefaults */ internal func loadDefaults() { stopDict = NSUserDefaults.standardUserDefaults().dictionaryForKey(kStopDictKey) as! [String: Int] notificationDict = NSUserDefaults.standardUserDefaults().dictionaryForKey(kNotificationDictKey) as! [String: Int] selectedStop = NSUserDefaults.standardUserDefaults().stringForKey(kSelectedStopKey)! } /** Save internal stopDict, notificationDict and selectedStop to NSUserDefaults */ internal func saveDefaults() { NSUserDefaults.standardUserDefaults().setObject(stopDict, forKey: kStopDictKey) NSUserDefaults.standardUserDefaults().setObject(notificationDict, forKey: kNotificationDictKey) NSUserDefaults.standardUserDefaults().setObject(selectedStop, forKey: kSelectedStopKey) NSUserDefaults.standardUserDefaults().synchronize() } // MARK: - Manage list of connections /** Delete all stored connections */ internal func nuke() { connections.removeAll(keepCapacity: false) } /** Set all connections' selected attribute to false */ internal func deselectAll() { for connection in connections { connection.selected = false } } // MARK: - Update Methods /** Update arrival countdowns for known connections and remove connections that lie in the past */ internal func updateConnectionCountdowns() { // Update arrival countdowns for currently known connections for connection in connections { connection.update() } // Remove connections that lie in the past connections = connections.filter { (c: Connection) -> Bool in return c.date.timeIntervalSinceNow > 0 } } /** Make a call to DVBAPI to update list of connections - parameter completion: handler when new data has been stored in connection list, will not be called on error */ internal func updateConnections(completion: (err: NSError?) -> Void) { if let selectedStopName = selectedStop { DVBAPI.DMRequest(selectedStopName, completion: { (data, err) -> () in print(data) completion(err: nil) }) } else { NSLog("Update error: No selected stop") completion(err: NSError(domain: "io.kilian.catchmybus", code: 0, userInfo: [NSLocalizedDescriptionKey: "Update error: No selected stop"])) } } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/23686-swift-parser-consumetoken.swift
10
222
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a{class A{func a{ { enum S } class case c,{
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/20608-no-stacktrace.swift
11
214
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [ { let a { struct d { deinit { class case ,
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/0372-swift-declcontext-lookupqualified.swift
13
252
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing enum S<T where g: c() -> { var d = F
apache-2.0
hotpoor-for-Liwei/LiteOS_Hackathon
Hakcathon_170108_哆啦I梦_wifind/ios/hackhuawei/LoginViewController.swift
2
6290
// // ViewController.swift // hackhuawei // // Created by 曾兆阳 on 2017/1/2. // Copyright © 2017年 曾兆阳. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { var backgroundView: UIImageView? var whiteView: UIImageView? var logoView: UIImageView? var closeView: UIImageView? var usernameInput: UITextField? var passwordInput: UITextField? var loginButton: UIButton? var registerButton: UIButton? let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height override func viewDidLoad() { super.viewDidLoad() // self.navigationController?.isNavigationBarHidden = true self.backgroundView = UIImageView(frame: self.view.bounds) self.backgroundView?.image = #imageLiteral(resourceName: "background") self.whiteView = UIImageView(image: #imageLiteral(resourceName: "whiteBox_halfCirle")) self.logoView = UIImageView(image: #imageLiteral(resourceName: "logo")) self.logoView?.frame.origin.x = (kScreenWidth - self.logoView!.frame.width) / 2 self.logoView?.frame.origin.y = 60 self.closeView = UIImageView(image: #imageLiteral(resourceName: "cross")) self.closeView?.frame.origin.x = (kScreenWidth - self.closeView!.frame.width) / 2 self.closeView?.frame.origin.y = 617 self.view.addSubview(self.backgroundView!) self.view.addSubview(self.whiteView!) self.view.addSubview(self.logoView!) self.view.addSubview(self.closeView!) self.usernameInput = UITextField(frame: CGRect(x: (kScreenWidth - 350) / 2, y: 305, width: 350, height: 48)) self.usernameInput?.backgroundColor = UIColor.orange self.usernameInput?.borderStyle = .line self.usernameInput?.contentVerticalAlignment = .center self.usernameInput?.contentHorizontalAlignment = .center self.usernameInput?.textAlignment = .center self.usernameInput?.placeholder = "用户名" self.passwordInput = UITextField(frame: CGRect(x: (kScreenWidth - 350) / 2, y: 371, width: 350, height: 48)) self.passwordInput?.backgroundColor = UIColor.orange self.passwordInput?.borderStyle = .line self.passwordInput?.contentVerticalAlignment = .center self.passwordInput?.contentHorizontalAlignment = .center self.passwordInput?.textAlignment = .center self.passwordInput?.isSecureTextEntry = true self.passwordInput?.delegate = self self.passwordInput?.placeholder = "密码" self.loginButton = UIButton(frame: CGRect(x: (kScreenWidth - 94) / 2, y: 460, width: 94, height: 18)) // self.loginButton?.backgroundColor = UIColor.blue self.loginButton?.setTitle("登录", for: .normal) self.loginButton?.setBackgroundImage(#imageLiteral(resourceName: "ellipse"), for: .selected) self.loginButton?.setBackgroundImage(#imageLiteral(resourceName: "ellipse"), for: .highlighted) self.loginButton?.setTitleColor(UIColor.black, for: .normal) self.loginButton?.titleLabel?.font = UIFont.systemFont(ofSize: 30) self.loginButton?.titleLabel?.sizeToFit() self.loginButton?.addTarget(self, action: #selector(LoginViewController.loginButtonClick), for: .touchUpInside) // self.loginButton?.frame.origin = CGPoint(x: (kScreenWidth - self.loginButton!.frame.size.width) / 2, y: 400) // self.registerButton = UIButton(frame: CGRect(x: (kScreenWidth - 200) / 2 + 120, y: 390, width: 80, height: 50)) // self.registerButton?.backgroundColor = UIColor.green // self.registerButton?.setTitle("Register", for: .normal) // print("haha") self.view.addSubview(self.usernameInput!) self.view.addSubview(self.passwordInput!) self.view.addSubview(self.loginButton!) // self.view.addSubview(self.registerButton!) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loginButtonClick() { let network = HWNetwork(path: "/login") network.request.httpBody = "username=\(self.usernameInput!.text!)&password=\(self.passwordInput!.text!)".data(using: String.Encoding.utf8) let dataTask: URLSessionTask = network.session.dataTask(with: network.request as URLRequest) { (data, resp, err) in let res = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) if res == "1" { let navController = HWNavigationController() let homeViewController = HomeViewController() homeViewController.username = self.usernameInput!.text print("aaa") homeViewController.title = self.usernameInput!.text print("bbb") navController.pushViewController(homeViewController, animated: false) navController.modalTransitionStyle = .crossDissolve self.modalTransitionStyle = .crossDissolve DispatchQueue.main.async { self.present(navController, animated: true) { // } } } else { DispatchQueue.main.async { let HUD = MBProgressHUD(view: self.view) self.view.addSubview(HUD!) HUD?.labelText = "用户名或密码错误" HUD?.mode = .text HUD?.dimBackground = true HUD?.show(animated: true, whileExecuting: { sleep(1) }, completionBlock: { HUD?.removeFromSuperview() }) } } } dataTask.resume() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
bsd-3-clause
ciiqr/contakt
contakt/contakt/Contact+photoOrDefault.swift
1
390
// // Contact+photoOrDefault.swift // contakt // // Created by William Villeneuve on 2016-01-22. // Copyright © 2016 William Villeneuve. All rights reserved. // import UIKit extension Contact { func photoOrDefault() -> UIImage { if let photo = self.photo { return photo } else { return Visuals.contactDefaultPhoto } } }
unlicense
pepibumur/Szimpla
Example/ServerTests/ServerSpec.swift
1
2042
import XCTest import Quick import Nimble import Swifter @testable import Szimpla class ServerSpec: QuickSpec { override func spec() { var subject: Server! var httpServer: MockServer! beforeEach { httpServer = MockServer() subject = Server(server: httpServer) } describe("-sessionConfiguration:") { it("should include the URLProtocol") { let inputConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let outputConfiguration = subject.sessionConfiguration(fromConfiguration: inputConfiguration) expect(outputConfiguration.protocolClasses?.first).to(be(UrlProtocol.self)) } } describe("-tearUp") { beforeEach { try! subject.tearUp() } it("should start the server") { expect(httpServer.startCalled) == true } it("should register the /stop endpoint") { expect(httpServer.routes.indexOf("/stop")).toNot(beNil()) } it("should register the /start endpoint") { expect(httpServer.routes.indexOf("/start")).toNot(beNil()) } it("should throw an error if we try to start twice") { expect { try subject.tearUp() }.to(throwError()) } } describe("-tearDown") { beforeEach { subject.tearDown() } it("should stop the server") { expect(httpServer.stopCalled) == true } } } } // MARK: - Private class MockServer: HttpServer { var startCalled: Bool = false var stopCalled: Bool = false override func start(listenPort: in_port_t, forceIPv4: Bool) throws { self.startCalled = true } override func stop() { self.stopCalled = true } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/09373-swift-sourcemanager-getmessage.swift
11
206
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let end = ( { if true { class case ,
mit
terflogag/OpenSourceController
Sources/OpenSourceControllerConfig.swift
1
1148
// // OpenSourceControllerConfig.swift // Pods // // Created by Florian Gabach on 08/03/2017. import UIKit /// Simple struct to hold settings public struct OpenSourceControllerConfig { /// Sub-stuct holding configuration relevant to UI presentation ! public struct UIConfig { /// Will be applied to the navigation bar public var backgroundColor: UIColor = Style.background /// Will be applied to licence text public var licenceBackgroundColor: UIColor = Style.background /// Will be applied to the navigation bar public var closeButtonColor: UIColor = Style.label /// Will be applied to licence text public var licenceTextColor: UIColor = Style.label /// Will be applied to licence text public var titleColor: UIColor = Style.label } /// Will be applied to the navigation bar title public var title: String = "Tiers library" /// Verbose mode for print log when licence are downloaded public var verbose: Bool = false /// UI-specific configuration. public init() { } public var uiConfig = UIConfig() }
mit
googlearchive/cannonball-ios
Cannonball/Theme.swift
1
2404
// // Copyright (C) 2018 Google, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation open class Theme { let name: String let words: [String] let pictures: [String] init?(jsonDictionary: [String : AnyObject]) { if let optionalName = jsonDictionary["name"] as? String, let optionalWords = jsonDictionary["words"] as? [String], let optionalPictures = jsonDictionary["pictures"] as? [String] { name = optionalName words = optionalWords pictures = optionalPictures } else { name = "" words = [] pictures = [] return nil } } open func getRandomWords(_ wordCount: Int) -> [String] { var wordsCopy = [String](words) // Sort randomly the elements of the dictionary. wordsCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the desired number of words. return Array(wordsCopy[0..<wordCount]) } open func getRandomPicture() -> String? { var picturesCopy = [String](pictures) // Sort randomly the pictures. picturesCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the first picture. return picturesCopy.first } class func getThemes() -> [Theme] { var themes = [Theme]() let path = Bundle.main.path(forResource: "Themes", ofType: "json")! if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let jsonArray = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [AnyObject] { themes = jsonArray.compactMap() { return Theme(jsonDictionary: $0 as! [String : AnyObject]) } } return themes } }
apache-2.0
cnoon/swift-compiler-crashes
crashes-duplicates/05209-swift-sourcemanager-getmessage.swift
11
373
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct A { var d = { class a<T { class func f: C { struct Q<d where T : NSObject { } typealias e { protocol A { let f = [Void{ return "\() -> ("[Void{ typealias e : T>: BooleanType, A : a { class case c,
mit
danielsaidi/KeyboardKit
Sources/KeyboardKit/Extensions/String+Chars.swift
1
246
// // String+Chars.swift // KeyboardKit // // Created by Daniel Saidi on 2021-02-03. // Copyright © 2021 Daniel Saidi. All rights reserved. // import Foundation extension String { var chars: [String] { self.map { String($0) } } }
mit
Goro-Otsubo/SimpleTVApp
SimpleTVApp/AppDelegate.swift
1
717
// // AppDelegate.swift // SimpleTVApp // // Created by 大坪五郎 on 2015/12/14. // Copyright © 2015年 Next Inc. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window:UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let tabBarCtrl = MainTabBarController(nibName: nil, bundle: nil) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.rootViewController = tabBarCtrl self.window!.makeKeyAndVisible() return true } }
mit
JasonCanCode/CRUDE-Futures
Pods/BrightFutures/BrightFutures/Future.swift
9
6532
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Result /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(@autoclosure(escaping) task: () -> T) -> Future<T, NoError> { return future(Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(task: () -> T) -> Future<T, NoError> { return future(Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T>(context: ExecutionContext, task: () -> T) -> Future<T, NoError> { return future(context: context) { () -> Result<T, NoError> in return Result(value: task()) } } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(@autoclosure(escaping) task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T, E>(context c: ExecutionContext, task: () -> Result<T, E>) -> Future<T, E> { let future = Future<T, E>(); c { future.complete(task()) } return future } /// Can be used to wrap a completionHandler-based Cocoa API /// The completionHandler should have two parameters: a value and an error. public func future<T, E>(method: ((T?, E?) -> Void) -> Void) -> Future<T, BrightFuturesError<E>> { return Future(resolver: { completion -> Void in method { value, error in if let value = value { completion(.Success(value)) } else if let error = error { completion(.Failure(.External(error))) } else { completion(.Failure(.IllegalState)) } } }) } /// Can be used to wrap a typical completionHandler-based Cocoa API /// The completionHandler should have one parameter: the error public func future<E>(method: ((E?) -> Void) -> Void) -> Future<Void, E> { return Future(resolver: { completion -> Void in method { error in if let error = error { completion(.Failure(error)) } else { completion(.Success()) } } }) } /// Can be used to wrap a typical completionHandler-based Cocoa API /// The completionHandler should have one parameter: the value public func future<T>(method: (T -> Void) -> Void) -> Future<T, NoError> { return Future(resolver: { completion -> Void in method { value in completion(.Success(value)) } }) } /// A Future represents the outcome of an asynchronous operation /// The outcome will be represented as an instance of the `Result` enum and will be stored /// in the `result` property. As long as the operation is not yet completed, `result` will be nil. /// Interested parties can be informed of the completion by using one of the available callback /// registration methods (e.g. onComplete, onSuccess & onFailure) or by immediately composing/chaining /// subsequent actions (e.g. map, flatMap, recover, andThen, etc.). /// /// For more info, see the project README.md public final class Future<T, E: ErrorType>: Async<Result<T, E>> { public typealias CompletionCallback = (result: Result<T,E>) -> Void public typealias SuccessCallback = T -> Void public typealias FailureCallback = E -> Void public required init() { super.init() } public required init(result: Future.Value) { super.init(result: result) } public init(value: T, delay: NSTimeInterval) { super.init(result: Result<T, E>(value: value), delay: delay) } public required init<A: AsyncType where A.Value == Value>(other: A) { super.init(other: other) } public convenience init(value: T) { self.init(result: Result(value: value)) } public convenience init(error: E) { self.init(result: Result(error: error)) } public required init(@noescape resolver: (result: Value -> Void) -> Void) { super.init(resolver: resolver) } } /// Short-hand for `lhs.recover(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> T) -> Future<T, NoError> { return lhs.recover(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Short-hand for `lhs.recoverWith(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E, E1>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> Future<T, E1>) -> Future<T, E1> { return lhs.recoverWith(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Can be used as the value type of a `Future` or `Result` to indicate it can never be a success. /// This is guaranteed by the type system, because `NoValue` has no possible values and thus cannot be created. public enum NoValue { }
mit
andreacremaschi/GEOSwift
Package.swift
1
635
// swift-tools-version:5.1 import PackageDescription let package = Package( name: "GEOSwift", platforms: [.iOS(.v9), .macOS(.v10_10), .tvOS(.v9)], products: [ .library(name: "GEOSwift", targets: ["GEOSwift"]) ], dependencies: [ .package(url: "https://github.com/GEOSwift/geos.git", .exact("5.0.0")) ], targets: [ .target( name: "GEOSwift", dependencies: ["geos"], path: "./GEOSwift/" ), .testTarget( name: "GEOSwiftTests", dependencies: ["GEOSwift"], path: "./GEOSwiftTests/" ) ] )
mit
airbnb/lottie-ios
Sources/Private/CoreAnimation/Layers/BaseCompositionLayer.swift
3
2527
// Created by Cal Stephens on 12/20/21. // Copyright © 2021 Airbnb Inc. All rights reserved. import QuartzCore // MARK: - BaseCompositionLayer /// The base type of `AnimationLayer` that can contain other `AnimationLayer`s class BaseCompositionLayer: BaseAnimationLayer { // MARK: Lifecycle init(layerModel: LayerModel) { baseLayerModel = layerModel super.init() setupSublayers() compositingFilter = layerModel.blendMode.filterName name = layerModel.name } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Called by CoreAnimation to create a shadow copy of this layer /// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init override init(layer: Any) { guard let typedLayer = layer as? Self else { fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))") } baseLayerModel = typedLayer.baseLayerModel super.init(layer: typedLayer) } // MARK: Internal /// Whether or not this layer render should render any visible content var renderLayerContents: Bool { true } /// Sets up the base `LayerModel` animations for this layer, /// and all child `AnimationLayer`s. /// - Can be overridden by subclasses, which much call `super`. override func setupAnimations(context: LayerAnimationContext) throws { var context = context if renderLayerContents { context = context.addingKeypathComponent(baseLayerModel.name) } try setupLayerAnimations(context: context) try setupChildAnimations(context: context) } func setupLayerAnimations(context: LayerAnimationContext) throws { let context = context.addingKeypathComponent(baseLayerModel.name) try addTransformAnimations(for: baseLayerModel.transform, context: context) if renderLayerContents { try addOpacityAnimation(for: baseLayerModel.transform, context: context) addVisibilityAnimation( inFrame: CGFloat(baseLayerModel.inFrame), outFrame: CGFloat(baseLayerModel.outFrame), context: context) } } func setupChildAnimations(context: LayerAnimationContext) throws { try super.setupAnimations(context: context) } // MARK: Private private let baseLayerModel: LayerModel private func setupSublayers() { if renderLayerContents, let masks = baseLayerModel.masks?.filter({ $0.mode != .none }), !masks.isEmpty { mask = MaskCompositionLayer(masks: masks) } } }
apache-2.0
victorchee/Live
Live/RTMP/Amf0.swift
1
12147
// // Amf0.swift // RTMP // // Created by VictorChee on 2016/12/21. // Copyright © 2016年 VictorChee. All rights reserved. // import Foundation class Amf0Data { enum Amf0DataType:UInt8 { case Amf0_Number = 0x00 case Amf0_Bool = 0x01 case Amf0_String = 0x02 /// Dictionary<String, Any?> case Amf0_Object = 0x03 case Amf0_MovieClip = 0x04 // Reserved, not suppported case Amf0_Null = 0x05 case Amf0_Undefined = 0x06 case Amf0_Reference = 0x07 /// Map case Amf0_ECMAArray = 0x08 case Amf0_ObjectEnd = 0x09 case Amf0_StrictArray = 0x0a case Amf0_Date = 0x0b case Amf0_LongString = 0x0c case Amf0_Unsupported = 0x0d case Amf0_RecordSet = 0x0e // Reserved, not supported case Amf0_XmlDocument = 0x0f case Amf0_TypedObject = 0x10 case Amf0_AVMplushObject = 0x11 } var dataInBytes = [UInt8]() var dataLength: Int { return dataInBytes.count } static func create(_ inputStream: ByteArrayInputStream) -> Amf0Data? { guard let amfTypeRawValue = inputStream.read() else { return nil } // 第一个Byte是AMF类型 guard let amf0Type = Amf0DataType(rawValue: amfTypeRawValue) else { return nil } var amf0Data: Amf0Data switch amf0Type { case .Amf0_Number: amf0Data = Amf0Number() case .Amf0_Bool: amf0Data = Amf0Boolean() case .Amf0_String: amf0Data = Amf0String() case .Amf0_Object: amf0Data = Amf0Object() case .Amf0_Null: amf0Data = Amf0Null() case .Amf0_Undefined: amf0Data = Amf0Undefined() case .Amf0_ECMAArray: amf0Data = Amf0ECMAArray() case .Amf0_StrictArray: amf0Data = Amf0StrictArray() case .Amf0_Date: amf0Data = Amf0Date() default: return nil } amf0Data.decode(inputStream) return amf0Data } func decode(_ inputStream: ByteArrayInputStream) { } } class Amf0Number: Amf0Data { var value: Double! override init() { } init(value: Any) { switch value { case let value as Double: self.value = value case let value as Int: self.value = Double(value) case let value as Int32: self.value = Double(value) case let value as UInt32: self.value = Double(value) case let value as Float64: self.value = Double(value) default: break } } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Number.rawValue) // 8B double value super.dataInBytes += value.bytes.reversed() return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skip self.value = NumberByteOperator.readDouble(inputStream) } static func decode(_ inputStream: ByteArrayInputStream) -> Double { // skip 1B amf type inputStream.read() return NumberByteOperator.readDouble(inputStream) } } class Amf0Null: Amf0Data { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // only 1B amf null type, no value super.dataInBytes.append(Amf0DataType.Amf0_Null.rawValue) return super.dataInBytes } set { super.dataInBytes = newValue } } } class Amf0Boolean: Amf0Data { private var value = false override init() { } init(value: Bool) { self.value = value } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Bool.rawValue) // Write value super.dataInBytes.append(value ? 0x01 : 0x00) return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skip self.value = (inputStream.read() == 0x01) } } class Amf0String: Amf0Data { private var value: String! override init() { } init(value: String) { self.value = value } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } let isLongString = UInt32(value.count) > UInt32(UInt16.max) // 1B type super.dataInBytes.append(isLongString ? Amf0DataType.Amf0_LongString.rawValue : Amf0DataType.Amf0_String.rawValue) let stringInBytes = [UInt8](value.utf8) // Value length if isLongString { // 4B, big endian super.dataInBytes += UInt32(stringInBytes.count).bigEndian.bytes } else { // 2B, big endian super.dataInBytes += UInt16(stringInBytes.count).bigEndian.bytes } // Value in bytes super.dataInBytes += stringInBytes return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped let stringLength = NumberByteOperator.readUInt16(inputStream) var stringInBytes = [UInt8](repeating: 0x00, count: Int(stringLength)) inputStream.read(&stringInBytes, maxLength: Int(stringLength)) self.value = String(bytes: stringInBytes, encoding: .utf8) } static func decode(_ inputStream: ByteArrayInputStream, isAmfObjectKey: Bool) -> String? { if !isAmfObjectKey { // Skip 1B amf type inputStream.read() } let stringLength = NumberByteOperator.readUInt16(inputStream) // 2B的长度数据 var stringInBytes = [UInt8](repeating: 0x00, count: Int(stringLength)) inputStream.read(&stringInBytes, maxLength: Int(stringLength)) return String(bytes: stringInBytes, encoding: .utf8) } } class Amf0Object: Amf0Data { /// 结尾 let endMark: [UInt8] = [0x00, 0x00, 0x09] var properties = [String: Amf0Data]() func setProperties(key: String, value: Any) { switch value { case let value as Double: properties[key] = Amf0Number(value: value) case let value as Int: properties[key] = Amf0Number(value: value) case let value as String: properties[key] = Amf0String(value: value) case let value as Bool: properties[key] = Amf0Boolean(value: value) default: properties[key] = Amf0Number(value: value) break } } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Object.rawValue) for (key, value) in properties { let keyInBytes = [UInt8](key.utf8) // Key super.dataInBytes += UInt16(keyInBytes.count).bigEndian.bytes super.dataInBytes += keyInBytes // Value super.dataInBytes += value.dataInBytes } super.dataInBytes += endMark return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped var buffer = [UInt8](repeating: 0x00, count:3) while true { // try read if catch the object end inputStream.tryRead(&buffer, maxLength: 3) if buffer[0] == endMark[0] && buffer[1] == endMark[1] && buffer[2] == endMark[2] { inputStream.read(&buffer, maxLength: 3) break } guard let key = Amf0String.decode(inputStream, isAmfObjectKey: true) else { return } guard let value = Amf0Data.create(inputStream) else { return } properties[key] = value } } } class Amf0StrictArray: Amf0Data { private var arrayItems = [Amf0Data]() override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_StrictArray.rawValue) // 4B count super.dataInBytes += UInt32(arrayItems.count).bigEndian.bytes // Items for item in arrayItems { super.dataInBytes += item.dataInBytes } return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped let arrayCount = NumberByteOperator.readUInt32(inputStream) for _ in 1...arrayCount { guard let item = Amf0Data.create(inputStream) else { return } arrayItems.append(item) } } } class Amf0ECMAArray: Amf0Object { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_ECMAArray.rawValue) super.dataInBytes += UInt32(properties.count).bigEndian.bytes for (key, value) in properties { super.dataInBytes += [UInt8](key.utf8) super.dataInBytes += value.dataInBytes } super.dataInBytes += endMark return super.dataInBytes } set { super.dataInBytes = newValue } } } class Amf0Undefined: Amf0Data { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // Only 1B amf type super.dataInBytes.append(Amf0DataType.Amf0_Undefined.rawValue) return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped // Amf type has been read, nothing still need to be decode } } class Amf0Date: Amf0Data { private var value: Date! override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_ECMAArray.rawValue) super.dataInBytes += (value.timeIntervalSince1970 * 1000).bytes.reversed() // 2B end super.dataInBytes += [0x00, 0x00] return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped value = Date(timeIntervalSince1970: NumberByteOperator.readDouble(inputStream) / 1000) } }
mit
catalanjrj/BarMate
BarMate/BarMate/LoginViewController.swift
1
2661
// // LoginViewController.swift // BarMate // // Created by Jorge Catalan on 6/10/16. // Copyright © 2016 Jorge Catalan. All rights reserved. // import UIKit import Firebase import FirebaseAuth class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // make buttons round self.loginButton.layer.cornerRadius = 8 self.hideKeyboardWhenTappedAround() FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth, user) in if user != nil { self.performSegueWithIdentifier("OrderSegue", sender: nil) } }) } @IBAction func unwindToLoginViewController(segue: UIStoryboardSegue) { try! FIRAuth.auth()!.signOut() } @IBAction func loginButton(sender: AnyObject) { FIRAuth.auth()?.signInWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: {user, error in if error != nil{ let alertController = UIAlertController(title: "Error", message:(error!.localizedDescription) , preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // ... } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "Try Again", style: .Default) { (action) in // ... } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) { } print(error!.localizedDescription) }else{ print("Success") self.performSegueWithIdentifier("OrderSegue", sender: sender) } }) } @IBOutlet weak var signUpButton: UIButton! } extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } }
cc0-1.0
DerikLu/SampleSwiftProject
SampleSwiftProject/AppDelegate.swift
1
2349
// // AppDelegate.swift // SampleSwiftProject // // Created by CGO on 2014/8/9. // Copyright (c) 2014年 DerikLu. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
ozpopolam/DoctorBeaver
DoctorBeaver/PetsRepository.swift
1
8647
// // Repository.swift // DoctorBeaver // // Created by Anastasia Stepanova-Kolupakhina on 11.05.16. // Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved. // import Foundation import CoreData protocol PetsRepositorySettable: class { // can get and set PetsRepository var petsRepository: PetsRepository! { get set } } // Obverver-subject protocol protocol PetsRepositoryStateSubject: class { var observers: [WeakPetsRepositoryStateObserver] { get set } func addObserver(observer: PetsRepositoryStateObserver) func removeObserver(observer: PetsRepositoryStateObserver) func notifyObservers() } // weak-wrapper for PetsRepositoryStateObserver class WeakPetsRepositoryStateObserver { weak var observer: PetsRepositoryStateObserver? init (_ observer: PetsRepositoryStateObserver) { self.observer = observer } } // Obverver protocol protocol PetsRepositoryStateObserver: class { func petsRepositoryDidChange(repository: PetsRepositoryStateSubject) } class PetsRepository: PetsRepositoryStateSubject { let modelName: String private lazy var appDocDirectory: NSURL = { let fileManager = NSFileManager.defaultManager() let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() private lazy var context: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator return managedObjectContext }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.appDocDirectory.URLByAppendingPathComponent(self.modelName) do { let options = [NSMigratePersistentStoresAutomaticallyOption: true] try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) } catch { print("Error adding persistentStore") } return coordinator }() private lazy var managedObjectModel: NSManagedObjectModel = { let modelUrl = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelUrl)! }() init(withModelName modelName: String) { self.modelName = modelName } func rollback() { context.rollback() } func saveOrRollback() -> Bool { if context.hasChanges { do { try context.save() notifyObservers() // notify all observers that some changes have happened in repository return true } catch { print("Error! Context cannot be saved!") context.rollback() return false } } else { return true } } // MARK: Insertion func insertTaskTypeItemBasicValues() -> TaskTypeItemBasicValues? { if let taskTypeItemBasicValues = TaskTypeItemBasicValues(insertIntoManagedObjectContext: context) { return taskTypeItemBasicValues } else { return nil } } func insertTaskTypeItem() -> TaskTypeItem? { if let taskTypeItem = TaskTypeItem(insertIntoManagedObjectContext: context) { return taskTypeItem } else { return nil } } func insertRealization() -> Realization? { if let realization = Realization(insertIntoManagedObjectContext: context) { return realization } else { return nil } } func insertTask() -> Task? { if let task = Task(insertIntoManagedObjectContext: context) { return task } else { return nil } } func insertPetBasicValues() -> PetBasicValues? { if let petBasicValues = PetBasicValues(insertIntoManagedObjectContext: context) { return petBasicValues } else { return nil } } func insertPet() -> Pet? { if let pet = Pet(insertIntoManagedObjectContext: context), let basicValues = fetchPetBasicValues() { pet.id = NSDate().timeIntervalSince1970 pet.basicValues = basicValues return pet } else { return nil } } func insertProxyPet() -> Pet? { // is used to store copy of settings of already existing pet if let pet = Pet(insertIntoManagedObjectContext: context) { pet.id = -1 return pet } return nil } // MARK: Counting func countAll(entityName: String) -> Int { let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.resultType = .CountResultType do { if let results = try context.executeFetchRequest(fetchRequest) as? [NSNumber] { if let count = results.first?.integerValue { return count } } } catch { print("Counting error!") } return 0 } // MARK: Fetching func fetchAllObjects(forEntityName entityName: String) -> [NSManagedObject] { let fetchRequest = NSFetchRequest(entityName: entityName) do { if let fetchResults = try context.executeFetchRequest(fetchRequest) as? [NSManagedObject] { return fetchResults } } catch { print("Fetching error!") } return [] } func fetchAllPets() -> [Pet] { let managedObjects = fetchAllObjects(forEntityName: Pet.entityName) var pets = [Pet]() for managedObject in managedObjects { if let pet = managedObject as? Pet { pets.append(pet) } } return pets } func fetchAllSelectedPets() -> [Pet] { let fetchRequest = NSFetchRequest(entityName: Pet.entityName) let predicate = NSPredicate(format: "%K == YES", Pet.Keys.selected.rawValue) fetchRequest.predicate = predicate do { if let results = try context.executeFetchRequest(fetchRequest) as? [Pet] { return results } } catch { print("Fetching error!") } return [] } func fetchPetBasicValues() -> PetBasicValues? { let fetchRequest = NSFetchRequest(entityName: PetBasicValues.entityName) fetchRequest.fetchLimit = 1 do { if let results = try context.executeFetchRequest(fetchRequest) as? [PetBasicValues] { return results.first } } catch { print("Fetching error!") } return nil } func fetchTaskTypeItem(withId id: Int) -> TaskTypeItem? { let fetchRequest = NSFetchRequest(entityName: TaskTypeItem.entityName) fetchRequest.fetchLimit = 1 let predicate = NSPredicate(format: "%K == %i", TaskTypeItem.Keys.id.rawValue, id) fetchRequest.predicate = predicate do { if let results = try context.executeFetchRequest(fetchRequest) as? [TaskTypeItem] { return results.first } } catch { print("Fetching error!") } return nil } func fetchAllTaskTypeItems() -> [TaskTypeItem] { let managedObjects = fetchAllObjects(forEntityName: TaskTypeItem.entityName) var taskTypeItems = [TaskTypeItem]() for managedObject in managedObjects { if let taskTypeItem = managedObject as? TaskTypeItem { taskTypeItems.append(taskTypeItem) } } return taskTypeItems } // MARK: Deletion func deleteObject(object: NSManagedObject) { context.deleteObject(object) } func deleteAllObjects(forEntityName entityName: String) { let fetchRequest = NSFetchRequest(entityName: entityName) do { if let fetchResults = try context.executeFetchRequest(fetchRequest) as? [NSManagedObject] { for object in fetchResults { context.deleteObject(object) } context.saveOrRollback() } } catch { print("Some error during cleaning!") } } // MARK: PetsRepositoryStateSubject var observers = [WeakPetsRepositoryStateObserver]() // observers for PetsRepository's state change func addObserver(observer: PetsRepositoryStateObserver) { observers.append(WeakPetsRepositoryStateObserver(observer)) } func removeObserver(observerToRemove: PetsRepositoryStateObserver) { for ind in 0..<observers.count { if let observer = observers[ind].observer { if observerToRemove === observer { observers.removeAtIndex(ind) break } } } } func notifyObservers() { for weakObserver in observers { weakObserver.observer?.petsRepositoryDidChange(self) } } } extension NSManagedObjectContext { public func saveOrRollback() { if hasChanges { do { try save() } catch { print("Context cannot be saved - roll back!") rollback() } } } }
mit
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Ground/MOptionWhistlesVsZombiesGround.swift
1
611
import Foundation class MOptionWhistlesVsZombiesGround { private let lanes:[MOptionWhistlesVsZombiesGroundLane] private let count:UInt32 init(area:MOptionWhistlesVsZombiesArea) { lanes = MOptionWhistlesVsZombiesGround.factoryLanes(area:area) count = UInt32(lanes.count) } //MARK: public func randomLane() -> MOptionWhistlesVsZombiesGroundLane { let random:UInt32 = arc4random_uniform(count) let randomInt:Int = Int(random) let lane:MOptionWhistlesVsZombiesGroundLane = lanes[randomInt] return lane } }
mit
zyhndesign/SDX_DG
sdxdg/sdxdg/VipUserServerModel.swift
1
612
// // VipUserServerModel.swift // sdxdg // // Created by lotusprize on 17/4/25. // Copyright © 2017年 geekTeam. All rights reserved. // import UIKit import ObjectMapper class VipUserServerModel: Mappable { var resultCode:Int? var success:Bool? var error_code:Int? var message:String? var object:[VipUser]? required init?(map: Map) { } func mapping(map: Map) { resultCode <- map["resultCode"] success <- map["success"] error_code <- map["error_code"] message <- map["message"] object <- map["object"] } }
apache-2.0
scottrhoyt/Jolt
Tests/TestingObjects/Protocols/RandomDataTest.swift
1
563
// // RandomDataTest.swift // Jolt // // Created by Scott Hoyt on 9/24/15. // Copyright © 2015 Scott Hoyt. All rights reserved. // protocol RandomDataTest { typealias OperandType : GenRandom func rands(count: Int, lowerBound: OperandType?, upperBound: OperandType?) -> [OperandType] } extension RandomDataTest { func rands(count: Int, lowerBound: OperandType? = nil, upperBound: OperandType? = nil) -> [OperandType] { return (0..<count).map {_ in OperandType.rand(lowerBound, upperBound: upperBound) } } }
mit
MBKwon/SwiftList
SwiftList/myList.swift
1
3026
// // myList.swift // SwiftList // // Created by Moonbeom KWON on 2017. 6. 15.. // Copyright © 2017년 mbkyle. All rights reserved. // import Foundation indirect enum myList <A> { case Nil case Cons(A, myList<A>) } extension myList { static func apply<T: NumericType>(values: T...) -> myList<T> { if values.count == 0 { return .Nil } else { if let first = values.first { return .Cons(first, apply(values: Array<T>(values.dropFirst())) ) } return .Nil } } static func apply<T: NumericType>(values: [T]) -> myList<T> { if values.count == 0 { return .Nil } else { if let first = values.first { return .Cons(first, apply(values: Array<T>(values.dropFirst())) ) } return .Nil } } } extension myList { func sum<T: NumericType>(ints: myList<T>) -> T { switch ints { case .Nil: return T(0) case let .Cons(x, xs): return x + sum(ints: xs) } } func product<T: NumericType>(ds: myList<T>) -> T { switch ds { case .Nil: return T(1.0) case let .Cons(x, xs): return x * product(ds: xs) } } } extension myList { func getHead<T>(_ list: myList<T>) -> myList<T> { switch list { case .Nil: return .Nil case let .Cons(x, xs): return .Cons(x, xs) } } func getTail<T>(_ list: myList<T>) -> myList<T> { switch list { case .Nil: return .Nil case let .Cons(_, xs): return xs } } } extension myList { func drop<T>(count: Int, list: myList<T>) -> myList<T> { switch count { case 0: return list default: return drop(count: count-1, list: getTail(list)) } } func dropWhile<T>(list: myList<T>, f: (T) -> Bool) -> myList<T> { switch list { case let .Cons(x, xs): if f(x) { return dropWhile(list: xs, f: f) } fallthrough default: return list } } } extension myList { func foldLeft<T>(acc: T, list: myList<T>, f: (T, T) -> T) -> T { switch list { case .Nil: return acc case let .Cons(x, xs): return foldLeft(acc: f(acc, x), list: xs, f: f) } } func foldRight<T>(acc: T, list: myList<T>, f: (T, T) -> T) -> T { switch list { case .Nil: return acc case let .Cons(x, xs): return f(x, foldRight(acc: acc, list: xs, f: f)) } } }
mit
benlangmuir/swift
test/ScanDependencies/module_deps.swift
4
7055
// RUN: %empty-directory(%t) // RUN: mkdir -p %t/clang-module-cache // RUN: %target-swift-frontend -scan-dependencies -module-cache-path %t/clang-module-cache %s -o %t/deps.json -I %S/Inputs/CHeaders -I %S/Inputs/Swift -emit-dependencies -emit-dependencies-path %t/deps.d -import-objc-header %S/Inputs/CHeaders/Bridging.h -swift-version 4 // Check the contents of the JSON output // RUN: %FileCheck -check-prefix CHECK_NO_CLANG_TARGET %s < %t/deps.json // Check the contents of the JSON output // RUN: %FileCheck %s -check-prefix CHECK-NO-SEARCH-PATHS < %t/deps.json // Check the make-style dependencies file // RUN: %FileCheck %s -check-prefix CHECK-MAKE-DEPS < %t/deps.d // Check that the JSON parses correctly into the canonical Swift data // structures. // RUN: mkdir -p %t/PrintGraph // RUN: cp %S/Inputs/PrintGraph.swift %t/main.swift // RUN: %target-build-swift %S/Inputs/ModuleDependencyGraph.swift %t/main.swift -o %t/main // RUN: %target-codesign %t/main // RUN: %target-run %t/main %t/deps.json // Ensure that round-trip serialization does not affect result // RUN: %target-swift-frontend -scan-dependencies -test-dependency-scan-cache-serialization -module-cache-path %t/clang-module-cache %s -o %t/deps.json -I %S/Inputs/CHeaders -I %S/Inputs/Swift -import-objc-header %S/Inputs/CHeaders/Bridging.h -swift-version 4 // RUN: %FileCheck -check-prefix CHECK_NO_CLANG_TARGET %s < %t/deps.json // Ensure that scanning with `-clang-target` makes sure that Swift modules' respective PCM-dependency-build-argument sets do not contain target triples. // RUN: %target-swift-frontend -scan-dependencies -module-cache-path %t/clang-module-cache %s -o %t/deps_clang_target.json -I %S/Inputs/CHeaders -I %S/Inputs/Swift -import-objc-header %S/Inputs/CHeaders/Bridging.h -swift-version 4 -clang-target %target-cpu-apple-macosx10.14 // Check the contents of the JSON output // RUN: %FileCheck -check-prefix CHECK_CLANG_TARGET %s < %t/deps_clang_target.json // REQUIRES: executable_test // REQUIRES: objc_interop import C import E import G import SubE // CHECK: "mainModuleName": "deps" /// --------Main module // CHECK-LABEL: "modulePath": "deps.swiftmodule", // CHECK-NEXT: sourceFiles // CHECK-NEXT: module_deps.swift // CHECK-NEXT: ], // CHECK-NEXT: "directDependencies": [ // CHECK-NEXT: { // CHECK-NEXT: "swift": "A" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "clang": "C" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "E" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "F" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "G" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "SubE" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "Swift" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "SwiftOnoneSupport" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "_Concurrency" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "_cross_import_E" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK: "extraPcmArgs": [ // CHECK-NEXT: "-Xcc", // CHECK-NEXT: "-target", // CHECK-NEXT: "-Xcc", // CHECK: "-fapinotes-swift-version=4" // CHECK-NOT: "error: cannot open Swift placeholder dependency module map from" // CHECK: "bridgingHeader": // CHECK-NEXT: "path": // CHECK-SAME: Bridging.h // CHECK-NEXT: "sourceFiles": // CHECK-NEXT: Bridging.h // CHECK-NEXT: BridgingOther.h // CHECK: "moduleDependencies": [ // CHECK-NEXT: "F" // CHECK-NEXT: ] /// --------Swift module A // CHECK-LABEL: "modulePath": "A.swiftmodule", // CHECK: directDependencies // CHECK-NEXT: { // CHECK-NEXT: "clang": "A" // CHECK-NEXT: } // CHECK-NEXT: { // CHECK-NEXT: "swift": "Swift" // CHECK-NEXT: }, /// --------Clang module C // CHECK-LABEL: "modulePath": "C.pcm", // CHECK: "sourceFiles": [ // CHECK-DAG: module.modulemap // CHECK-DAG: C.h // CHECK: directDependencies // CHECK-NEXT: { // CHECK-NEXT: "clang": "B" // CHECK: "moduleMapPath" // CHECK-SAME: module.modulemap // CHECK: "contextHash" // CHECK-SAME: "{{.*}}" // CHECK: "commandLine": [ // CHECK-NEXT: "-frontend" // CHECK-NEXT: "-only-use-extra-clang-opts" // CHECK-NOT: "BUILD_DIR/bin/clang" // CHECK: "-Xcc" // CHECK-NEXT: "-resource-dir" // CHECK-NEXT: "-Xcc" // CHECK-NEXT: "BUILD_DIR/lib/swift/clang" // CHECK: "-fsystem-module", // CHECK-NEXT: "-emit-pcm", // CHECK-NEXT: "-module-name", // CHECK-NEXT: "C" // CHECK: "capturedPCMArgs": [ // CHECK-NEXT: [, // CHECK-NEXT: "-Xcc", // CHECK-NEXT: "-fapinotes-swift-version=4" // CHECK-NEXT: ] // CHECK-NEXT: ] /// --------Swift module E // CHECK: "swift": "E" // CHECK-LABEL: modulePath": "E.swiftmodule" // CHECK: "directDependencies" // CHECK-NEXT: { // CHECK-NEXT: "swift": "Swift" // CHECK: "moduleInterfacePath" // CHECK-SAME: E.swiftinterface /// --------Swift module F // CHECK: "modulePath": "F.swiftmodule", // CHECK-NEXT: "sourceFiles": [ // CHECK-NEXT: ], // CHECK-NEXT: "directDependencies": [ // CHECK-NEXT: { // CHECK-NEXT: "clang": "F" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "Swift" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "SwiftOnoneSupport" // CHECK-NEXT: } // CHECK-NEXT: ], /// --------Swift module G // CHECK-LABEL: "modulePath": "G.swiftmodule" // CHECK: "directDependencies" // CHECK-NEXT: { // CHECK-NEXT: "clang": "G" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "Swift" // CHECK-NEXT: }, // CHECK-NEXT: { // CHECK-NEXT: "swift": "SwiftOnoneSupport" // CHECK-NEXT: } // CHECK-NEXT: ], // CHECK-NEXT: "details": { // CHECK: "contextHash": "{{.*}}", // CHECK: "commandLine": [ // CHECK: "-compile-module-from-interface" // CHECK: "-target" // CHECK: "-module-name" // CHECK: "G" // CHECK: "-swift-version" // CHECK: "5" // CHECK: ], // CHECK_NO_CLANG_TARGET: "extraPcmArgs": [ // CHECK_NO_CLANG_TARGET-NEXT: "-Xcc", // CHECK_NO_CLANG_TARGET-NEXT: "-target", // CHECK_CLANG_TARGET: "extraPcmArgs": [ // CHECK_CLANG_TARGET-NEXT: "-Xcc", // CHECK_CLANG_TARGET-NEXT: "-fapinotes-swift-version={{.*}}" // CHECK_CLANG_TARGET-NEXT: ] /// --------Swift module Swift // CHECK-LABEL: "modulePath": "Swift.swiftmodule", // CHECK: directDependencies // CHECK-NEXT: { // CHECK-NEXT: "clang": "SwiftShims" /// --------Clang module B // CHECK-LABEL: "modulePath": "B.pcm" // CHECK-NEXT: sourceFiles // CHECK-DAG: module.modulemap // CHECK-DAG: B.h // CHECK: directDependencies // CHECK-NEXT: { // CHECK-NEXT: "clang": "A" // CHECK-NEXT: } /// --------Clang module SwiftShims // CHECK-LABEL: "modulePath": "SwiftShims.pcm", // CHECK-NO-SEARCH-PATHS-NOT: "-prebuilt-module-cache-path" // Check make-style dependencies // CHECK-MAKE-DEPS: module_deps.swift // CHECK-MAKE-DEPS-SAME: A.swiftinterface // CHECK-MAKE-DEPS-SAME: G.swiftinterface // CHECK-MAKE-DEPS-SAME: B.h // CHECK-MAKE-DEPS-SAME: F.h // CHECK-MAKE-DEPS-SAME: Bridging.h // CHECK-MAKE-DEPS-SAME: BridgingOther.h // CHECK-MAKE-DEPS-SAME: module.modulemap
apache-2.0
benlangmuir/swift
test/decl/circularity.swift
4
3169
// RUN: %target-typecheck-verify-swift // N.B. Validating the pattern binding initializer for `pickMe` used to cause // recursive validation of the VarDecl. Check that we don't regress now that // this isn't the case. public struct Cyclic { static func pickMe(please: Bool) -> Int { return 42 } public static let pickMe = Cyclic.pickMe(please: true) } struct Node {} struct Parameterized<Value, Format> { func please<NewValue>(_ transform: @escaping (_ otherValue: NewValue) -> Value) -> Parameterized<NewValue, Format> { fatalError() } } extension Parameterized where Value == [Node], Format == String { static var pickMe: Parameterized { fatalError() } } extension Parameterized where Value == Node, Format == String { static let pickMe = Parameterized<[Node], String>.pickMe.please { [$0] } } enum Loop: Circle { struct DeLoop { } } protocol Circle { typealias DeLoop = Loop.DeLoop } class Base { static func foo(_ x: Int) {} } class Sub: Base { var foo = { () -> Int in let x = 42 // FIXME: Bogus diagnostic return foo(1) // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} }() } extension Float { static let pickMe: Float = 1 } extension SIMD3 { init(_ scalar: Scalar) { self.init(repeating: scalar) } } extension SIMD3 where SIMD3.Scalar == Float { static let pickMe = SIMD3(.pickMe) } // Test case with circular overrides protocol P { associatedtype A // expected-note@-1 {{protocol requires nested type 'A'; do you want to add it?}} func run(a: A) } class C1 { func run(a: Int) {} } class C2: C1, P { // expected-note@-1 {{through reference here}} override func run(a: A) {} // expected-error@-1 {{circular reference}} // expected-note@-2 {{while resolving type 'A'}} // expected-note@-3 2{{through reference here}} } // Another crash to the above open class G1<A> { open func run(a: A) {} } class C3: G1<A>, P { // expected-error@-1 {{type 'C3' does not conform to protocol 'P'}} // expected-error@-2 {{cannot find type 'A' in scope}} // expected-note@-3 {{through reference here}} override func run(a: A) {} // expected-error@-1 {{method does not override any method from its superclass}} // expected-error@-2 {{circular reference}} // expected-note@-3 2 {{through reference here}} // expected-note@-4 {{while resolving type 'A'}} } // Another case that triggers circular override checking. protocol P1 { associatedtype X = Int init(x: X) } class C4 { required init(x: Int) {} } class D4 : C4, P1 { // expected-note 3 {{through reference here}} required init(x: X) { // expected-error {{circular reference}} // expected-note@-1 {{while resolving type 'X'}} // expected-note@-2 2{{through reference here}} super.init(x: x) } } // https://github.com/apple/swift/issues/54662 // N.B. This used to compile in 5.1. protocol P_54662 { } class C_54662 { // expected-note {{through reference here}} typealias Nest = P_54662 // expected-error {{circular reference}} expected-note {{through reference here}} } extension C_54662: C_54662.Nest { }
apache-2.0
insanoid/SwiftyJSONAccelerator
Core/Generator/Model-File-Components/PropertyComponent.swift
1
1368
// // PropertyComponent.swift // SwiftyJSONAccelerator // // Created by Karthik on 09/07/2016. // Copyright © 2016 Karthikeya Udupa K M. All rights reserved. // import Foundation /// A strucutre to store various attributes related to a single property. struct PropertyComponent { /// Name of the property. var name: String /// Type of the property. var type: String /// Constant name that is to be used to encode, decode and read from JSON. var constantName: String /// Original key in the JSON file. var key: String /// Nature of the property, if it is a value type, an array of a value type or an object. var propertyType: PropertyType /// Initialise a property component. /// /// - Parameters: /// - name: Name of the property. /// - type: Type of the property. /// - constantName: Constant name that is to be used to encode, decode and read from JSON. /// - key: Original key in the JSON file. /// - propertyType: Nature of the property, if it is a value type, an array of a value type or an object. init(_ name: String, _ type: String, _ constantName: String, _ key: String, _ propertyType: PropertyType) { self.name = name self.type = type self.constantName = constantName self.key = key self.propertyType = propertyType } }
mit
Kametrixom/Swift-SyncAsync
SyncAsync.playground/Pages/toAsync.xcplaygroundpage/Contents.swift
1
3685
//: [Previous](@previous) import XCPlayground //: The `toAsync` function is the reverse of the `toSync` function. It takes a synchronous function and returns its asynchronous variant //: Let's create a synchronous function func add(a: Int, b: Int) -> Int { return a + b } //: To make it asynchronous, just call `toAsync` on it. The resulting function takes the arguments of the synchronous function plus a completion handler toAsync(add)(1, 2) { result in print("Added: \(result)") } waitABit() // Waits a bit so that the outputs don't get messed up (because it's asynchronous), see Utils.swift //: Like the `toSync` function, the `toAsync` function is overloaded for it to be able to take up to four inputs and an unlimited amount of outputs. To demonstrate this, we'll create a few synchronous functions // Our own error type enum Error: ErrorType { case LessThanZero case DivisionByZero } func sayHi(to: String, isBuddy: Bool) -> (speech: String, friendly: Bool) { switch (to, isBuddy) { case ("Bob", _): return ("...", false) case (_, true): return ("Hey man", true) case (let s, _): return ("Hello, \(s)", true) } } func product(from: Int, through: Int, steps: Int) -> Int { return from.stride(through: through, by: steps).reduce(1, combine: *) } func factorial(n: Int) throws -> Int { guard n >= 0 else { throw Error.LessThanZero } return n < 2 ? 1 : try factorial(n - 1) * n } func divide12345By(val: Double) throws -> (Double, Double, Double, Double, Double) { guard val != 0 else { throw Error.DivisionByZero } return (1 / val, 2 / val, 3 / val, 4 / val, 5 / val) } //: Simply call `toAsync` to convert these to asynchronoous functions let asyncHi = toAsync(sayHi) let asyncProd = toAsync(product) let asyncFactorial = toAsync(factorial) let asyncDivision = toAsync(divide12345By) //: As you can see from the types, throwing functions automatically get converted to functions that take a completion handler, executed when succeeded, and an error handler, executed when an error occured. As with `toSync`, parameter names cannot be preserved. asyncHi("Paul", true) { debugPrint($0) } waitABit() asyncProd(4, 10, 2) { debugPrint($0) } waitABit() asyncFactorial(-3, completionHandler: { debugPrint($0) }, errorHandler: { debugPrint($0) }) waitABit() asyncDivision(19, completionHandler: { debugPrint($0) }, errorHandler: { debugPrint($0) }) waitABit() //: And yes if you really want to, you can chain `toAsync` and `toSync` even though this is utter nonsense toSync(toAsync(sayHi))("Bob", false) /*: I hope this small library helps you, it was really fun to write it anyways. The source file was partly generated automatically, errors are unlikely, also due to the very strict function signatures, however if you happen to find an error, please let me know (@Kametrixom on Twitter, Reddit, StackOverflow, Github, ...) and I'll see what I can do. Suggestions and critique are very welcome as well. If you don't like that the functions are so minimized, I'm sorry, but otherwise it would get very big. Also sorry for any typos, english isn't my native language. If you're able to use my library for anything useful, I wouldn't mind a mention on Twitter ;) Inspiration came from StackOverflow where people often want to make asynchronous tasks synchronous (usually that's a bad thing). They get replies such as "These functions are asynchronous for a reason, don't fight it", etc. but sometimes it's actually pretty useful to have them synchronous, as I mentioned in the beginning. Recently I've been getting into Haskell, where higher-order functions are the norm, which made me write this library in this higher-order function style (I like it :D). */
mit
adrfer/swift
validation-test/compiler_crashers_fixed/26313-llvm-densemapbase-llvm-densemap-swift-silbasicblock.swift
13
275
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let d{}struct Q{ protocol a:d { {}protocol A:A { }}struct da
apache-2.0
slavapestov/swift
validation-test/compiler_crashers_fixed/28126-swift-getbuiltinvaluedecl.swift
4
289
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func<{class a{enum S<T{class C{func f{{{}let a{struct S<f:f.c}}}{}var b:T
apache-2.0
elpassion/el-space-ios
ELSpace/Network/ApiClient/RequestPerformer.swift
1
1401
import Alamofire import RxSwift protocol Requesting { func request(_ url: URLConvertible, method: HTTPMethod, parameters: Parameters?, encoding: ParameterEncoding?, headers: HTTPHeaders?) -> Observable<Response> } class RequestPerformer: Requesting { init(sessionManager: RequestWrapper) { self.sessionManager = sessionManager } // MARK: - Requesting func request(_ url: URLConvertible, method: HTTPMethod, parameters: Parameters?, encoding: ParameterEncoding?, headers: HTTPHeaders?) -> Observable<Response> { return sessionManager.request(url, method: method, parameters: parameters, encoding: { guard let encoding = encoding else { return URLEncoding.queryString } return encoding }(), headers: headers) .map { (response, data) -> Response in return Response(statusCode: response.statusCode, data: data) } } // MARK: - Private private let sessionManager: RequestWrapper }
gpl-3.0
joerocca/GitHawk
Classes/Settings/GithubClient+APIStatus.swift
1
855
// // GithubClient+APIStatus.swift // Freetime // // Created by Ryan Nystrom on 8/27/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation extension GithubClient { enum APIStatus: String { case good, minor, major } func fetchAPIStatus(completion: @escaping (Result<APIStatus>) -> Void) { request(Request( url: "https://status.github.com/api/status.json", method: .get, completion: { (response, _) in if let json = response.value as? [String: Any], let statusString = json["status"] as? String, let status = APIStatus(rawValue: statusString) { completion(.success(status)) } else { completion(.error(nil)) } })) } }
mit
jisudong/study
Study/Study/Study_RxSwift/Platform/DataStructures/Queue.swift
1
4061
// // Queue.swift // Study // // Created by syswin on 2017/7/31. // Copyright © 2017年 syswin. All rights reserved. // struct Queue<T>: Sequence { typealias Generator = AnyIterator<T> private let _resizeFactor = 2 private var _storage: ContiguousArray<T?> private var _count = 0 private var _pushNextIndex = 0 private let _initialCapacity: Int init(capacity: Int) { _initialCapacity = capacity _storage = ContiguousArray<T?>(repeating: nil, count: capacity) } private var dequeueIndex: Int { let index = _pushNextIndex - count return index < 0 ? index + _storage.count : index } var isEmpty: Bool { return count == 0 } var count: Int { return _count } func peek() -> T { precondition(count > 0) return _storage[dequeueIndex]! } mutating private func resizeTo(_ size: Int) { var newStorage = ContiguousArray<T?>(repeating: nil, count: size) let count = _count let dequeueIndex = self.dequeueIndex let spaceToEndOfQueue = _storage.count - dequeueIndex let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) let numberOfElementsInSecondBatch = count - countElementsInFirstBatch newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] _count = count _pushNextIndex = count _storage = newStorage // print("resizeTo --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } mutating func enqueue(_ element: T) { if count == _storage.count { resizeTo(Swift.max(_storage.count, 1) * _resizeFactor) } _storage[_pushNextIndex] = element _pushNextIndex += 1 _count += 1 if _pushNextIndex >= _storage.count { _pushNextIndex -= _storage.count } // print("enqueue --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } private mutating func dequeueElementOnly() -> T { precondition(count > 0) let index = dequeueIndex defer { _storage[index] = nil _count -= 1 // print("dequeueElementOnly --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } return _storage[index]! } mutating func dequeue() -> T? { if self.count == 0 { return nil } defer { let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) if _count < downsizeLimit && downsizeLimit >= _initialCapacity { resizeTo(_storage.count / _resizeFactor) } // print("dequeue ---- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } return dequeueElementOnly() } func makeIterator() -> AnyIterator<T> { var i = dequeueIndex var count = _count return AnyIterator { if count == 0 { return nil } defer { count -= 1 i += 1 } if i >= self._storage.count { i -= self._storage.count } return self._storage[i] } } }
mit
ahoppen/swift
test/Interop/Cxx/class/inline-function-codegen/static-var-init-calls-function-irgen.swift
4
417
// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop -validate-tbd-against-ir=none | %FileCheck %s // TODO: See why -validate-tbd-against-ir=none is needed here (SR-14069) import StaticVarInitCallsFunction public func getInitializedStaticVar() -> CInt { return initializeStaticVar() } // CHECK: define linkonce_odr{{( dso_local)?}} i32 @{{_Z9incrementi|"\?increment@@YAHH@Z"}}(i32 %t)
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/28000-swift-astcontext-getimplicitlyunwrappedoptionaldecl.swift
11
440
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func b{{let:{struct X<T:T.a}}if{enum S<T{func b
apache-2.0
overtake/TelegramSwift
Telegram-Mac/ColdStartPasslockController.swift
1
3591
// // ColdStartPasslockController.swift // Telegram // // Created by Mikhail Filimonov on 03.11.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit class ColdStartPasslockController: ModalViewController { private let valueDisposable = MetaDisposable() private let logoutDisposable = MetaDisposable() private let logoutImpl:() -> Signal<Never, NoError> private let checkNextValue: (String)->Bool init(checkNextValue:@escaping(String)->Bool, logoutImpl:@escaping()->Signal<Never, NoError>) { self.checkNextValue = checkNextValue self.logoutImpl = logoutImpl super.init(frame: NSMakeRect(0, 0, 350, 350)) self.bar = .init(height: 0) } override var isVisualEffectBackground: Bool { return false } override var isFullScreen: Bool { return true } override var background: NSColor { return self.containerBackground } private var genericView:PasscodeLockView { return self.view as! PasscodeLockView } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidLoad() { super.viewDidLoad() genericView.logoutImpl = { [weak self] in guard let window = self?.window else { return } confirm(for: window, information: strings().accountConfirmLogoutText, successHandler: { [weak self] _ in guard let `self` = self else { return } _ = showModalProgress(signal: self.logoutImpl(), for: window).start(completed: { [weak self] in delay(0.2, closure: { [weak self] in self?.close() }) }) }) } var locked = false valueDisposable.set((genericView.value.get() |> deliverOnMainQueue).start(next: { [weak self] value in guard let `self` = self, !locked else { return } if !self.checkNextValue(value) { self.genericView.input.shake() } else { locked = true } })) genericView.update(hasTouchId: false) readyOnce() } override var closable: Bool { return false } override func escapeKeyAction() -> KeyHandlerResult { return .invoked } override func firstResponder() -> NSResponder? { if !(window?.firstResponder is NSText) { return genericView.input } let editor = self.window?.fieldEditor(true, for: genericView.input) if window?.firstResponder != editor { return genericView.input } return editor } override var containerBackground: NSColor { return theme.colors.background.withAlphaComponent(1.0) } override var handleEvents: Bool { return true } override var cornerRadius: CGFloat { return 0 } override var handleAllEvents: Bool { return true } override var responderPriority: HandlerPriority { return .supreme } deinit { logoutDisposable.dispose() valueDisposable.dispose() self.window?.removeAllHandlers(for: self) } override func viewClass() -> AnyClass { return PasscodeLockView.self } }
gpl-2.0
popodidi/HTagView
HTagView/Classes/HTag.swift
1
8793
// // HTag.swift // Pods // // Created by Chang, Hao on 12/12/2016. // // import UIKit protocol HTagDelegate: class { func tagClicked(_ sender: HTag) func tagCancelled(_ sender: HTag) } public class HTag: UIView { weak var delegate: HTagDelegate? // MARK: - HTag Configuration /** Type of tag */ var tagType: HTagType = .cancel { didSet { updateAll() } } /** Title of tag */ var tagTitle: String = "" { didSet { updateAll() } } /** Main background color of tags */ var tagMainBackColor : UIColor = UIColor.white { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Main text color of tags */ var tagMainTextColor : UIColor = UIColor.black { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Secondary background color of tags */ var tagSecondBackColor : UIColor = UIColor.gray { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Secondary text color of tags */ var tagSecondTextColor : UIColor = UIColor.white { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** The border width to height ratio of HTags. */ var tagBorderWidth :CGFloat = 1 { didSet { updateBorder() } } /** The border color to height ratio of HTags. */ var tagBorderColor :CGColor? = UIColor.darkGray.cgColor { didSet { updateBorder() } } /** The corner radius to height ratio of HTags. */ var tagCornerRadiusToHeightRatio: CGFloat = 0.2 { didSet { updateBorder() } } /** The content EdgeInsets of HTags, which would automatically adjust the position in `.cancel` type. On the other word, usages are the same in both types. */ var tagContentEdgeInsets: UIEdgeInsets = UIEdgeInsets() { didSet { updateAll()} } /** The distance between cancel icon and text */ var tagCancelIconRightMargin: CGFloat = 4 { didSet { updateAll()} } /** The Font of HTags. */ var tagFont: UIFont = UIFont.systemFont(ofSize: 17) { didSet { updateAll() } } /** Specified Width of Tag */ var tagSpecifiedWidth: CGFloat? = nil { didSet { layoutSubviews() } } /** Maximum Width of Tag */ var tagMaximumWidth: CGFloat? = nil { didSet { layoutSubviews() } } /** Elevation of Tag */ var tagElevation: CGFloat = 0 { didSet { layoutSubviews() } } // MARK: - status private(set) var isSelected: Bool = false // MARK: - Subviews var button: UIButton = UIButton(type: .system) var cancelButton: UIButton = UIButton(type: .system) // MARK: - Init override init(frame: CGRect){ super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } deinit { button.removeObserver(self, forKeyPath: "highlighted") } // MARK: - Configure func configure(){ clipsToBounds = true self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped))) setupButton() setupCancelButton() updateAll() } // MARK: - button func setupButton() { addSubview(button) button.addTarget(self, action: #selector(tapped), for: .touchUpInside) button.addObserver(self, forKeyPath: "highlighted", options: .new, context: nil) } func setHighlight(_ highlighted: Bool) { let color = isSelected ? tagMainBackColor : tagSecondBackColor backgroundColor = highlighted ? color.darker() : color layer.shadowRadius = highlighted ? 0 : tagElevation * 0.1 } func setSelected(_ selected: Bool) { isSelected = selected updateTitlesColorsAndFontsDueToSelection() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case "highlighted": guard let highlighted = change?[.newKey] as? Bool else { break } setHighlight(highlighted) default: break } } // MARK: - cancel button func setupCancelButton() { cancelButton.setImage(UIImage(named: "close_small", in: Bundle(for: self.classForCoder), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) cancelButton.addTarget(self, action: #selector(cancelled), for: .touchUpInside) addSubview(cancelButton) cancelButton.isHidden = tagType == .select } // MARK: - Layout public override func layoutSubviews() { button.sizeToFit() // set origin if tagType == .select { button.frame.origin = CGPoint(x: tagContentEdgeInsets.left, y: tagContentEdgeInsets.top) } else { let cancelButtonSide: CGFloat = 16 cancelButton.frame.size = CGSize(width: cancelButtonSide, height: cancelButtonSide) cancelButton.frame.origin = CGPoint(x: tagContentEdgeInsets.left , y: tagContentEdgeInsets.top + button.frame.height/2 - cancelButtonSide/2) button.frame.origin = CGPoint(x: tagContentEdgeInsets.left + cancelButtonSide + tagCancelIconRightMargin , y: tagContentEdgeInsets.top) } // set shadow if tagElevation != 0 { clipsToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = .zero layer.shadowRadius = tagElevation * 0.1 } // set size let tagHeight = button.frame.maxY + tagContentEdgeInsets.bottom var tagWidth: CGFloat = 0 if let tagSpecifiedWidth = tagSpecifiedWidth { tagWidth = tagSpecifiedWidth } else { tagWidth = button.frame.maxX + tagContentEdgeInsets.right } var shouldSetButtonWidth: Bool = false if let maxWidth = tagMaximumWidth, maxWidth < tagWidth { tagWidth = maxWidth shouldSetButtonWidth = true } else if tagSpecifiedWidth != nil { shouldSetButtonWidth = true } frame.size = CGSize(width: tagWidth, height: tagHeight) if shouldSetButtonWidth { button.frame.size.width = tagWidth - cancelButton.frame.width - tagCancelIconRightMargin - tagContentEdgeInsets.left - tagContentEdgeInsets.right } } func updateAll() { cancelButton.isHidden = tagType == .select updateTitlesColorsAndFontsDueToSelection() updateBorder() button.sizeToFit() layoutIfNeeded() invalidateIntrinsicContentSize() } func updateTitlesColorsAndFontsDueToSelection() { backgroundColor = isSelected ? tagMainBackColor : tagSecondBackColor let textColor = isSelected ? tagMainTextColor : tagSecondTextColor var attributes: [NSAttributedString.Key: Any] = [:] attributes[.font] = tagFont attributes[.foregroundColor] = textColor button.setAttributedTitle(NSAttributedString(string: tagTitle, attributes: attributes), for: .normal) if tagType == .cancel { cancelButton.tintColor = textColor } } func updateBorder() { layer.borderWidth = tagBorderWidth layer.borderColor = tagBorderColor layer.cornerRadius = bounds.height * tagCornerRadiusToHeightRatio } // MARK: - User interaction @objc func tapped(){ delegate?.tagClicked(self) } @objc func cancelled() { delegate?.tagCancelled(self) } } extension UIColor { func lighter(by percentage: CGFloat = 30.0) -> UIColor? { return self.adjust(by: abs(percentage) ) } func darker(by percentage: CGFloat = 30.0) -> UIColor? { return self.adjust(by: -1 * abs(percentage) ) } func adjust(by percentage: CGFloat = 30.0) -> UIColor? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: a) }else{ return nil } } }
mit
brentsimmons/Evergreen
Account/Sources/Account/FeedWrangler/FeedWranglerFeedItemId.swift
1
277
// // File.swift // // // Created by Jonathan Bennett on 2021-01-14. // import Foundation struct FeedWranglerFeedItemId: Hashable, Codable { let feedItemID: Int enum CodingKeys: String, CodingKey { case feedItemID = "feed_item_id" } }
mit
austinzheng/swift-compiler-crashes
crashes-duplicates/11228-swift-sourcemanager-getmessage.swift
11
237
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func b { case ( { class A { protocol P { var d = [ { { class case ,
mit
lfaoro/Cast
Cast/PreferenceManager.swift
1
2386
// // Created by Leonardo on 10/16/15. // Copyright © 2015 Leonardo Faoro. All rights reserved. // import Cocoa // Keys in a variable to avoid mistakes private let gistServiceKey = "gistService" private let imageServiceKey = "imageService" private let shortenServiceKey = "shortenService" private let recentActionsKey = "recentActions" private let secretGistsAvailableKey = "secretGistsAvailable" private let gistIsPublicKey = "gistIsPublic" class PreferenceManager { private let userDefaults = NSUserDefaults.standardUserDefaults() init() { registerDefaults() } func registerDefaults() { let standardDefaults = [ gistServiceKey: "GitHub", imageServiceKey: "imgur", shortenServiceKey: "Is.Gd", recentActionsKey: ["Cast": "http://cast.lfaoro.com"], secretGistsAvailableKey: true, gistIsPublicKey: false, ] userDefaults.registerDefaults(standardDefaults) } // MARK: - Defaults properties abstraction // MARK: Gist Options var gistService: String? { get { return userDefaults.objectForKey(gistServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: gistServiceKey) switch newValue! { case "GitHub": secretGistsAvailable = true default: secretGistsAvailable = false } } } var secretGistsAvailable: Bool? { get { return userDefaults.objectForKey(secretGistsAvailableKey) as? Bool } set { userDefaults.setObject(newValue, forKey: secretGistsAvailableKey) } } var gistIsPublic: Bool? { get { return userDefaults.objectForKey(gistIsPublicKey) as? Bool } set { userDefaults.setObject(newValue, forKey: gistIsPublicKey) } } // MARK: Image options var imageService: String? { get { return userDefaults.objectForKey(imageServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: imageServiceKey) } } // MARK: Shortening Options // Binded from OptionsWindow > Segmented control var shortenService: String? { get { return userDefaults.objectForKey(shortenServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: shortenServiceKey) } } var recentActions: [String: String]? { get { return userDefaults.objectForKey(recentActionsKey) as? [String: String] } set { userDefaults.setObject(newValue, forKey: recentActionsKey) app.statusBarItem.menu = createMenu(app.menuSendersAction) } } }
mit
goktugyil/EZSwiftExtensions
Sources/TimePassed.swift
1
1117
// // TimePassed.swift // EZSwiftExtensions // // Created by Jaja Yting on 24/08/2018. // Copyright © 2018 Goktug Yilmaz. All rights reserved. // import Foundation public enum TimePassed { case year(Int) case month(Int) case day(Int) case hour(Int) case minute(Int) case second(Int) case now } extension TimePassed: Equatable { public static func ==(lhs: TimePassed, rhs: TimePassed) -> Bool { switch(lhs, rhs) { case (.year(let a), .year(let b)): return a == b case (.month(let a), .month(let b)): return a == b case (.day(let a), .day(let b)): return a == b case (.hour(let a), .hour(let b)): return a == b case (.minute(let a), .minute(let b)): return a == b case (.second(let a), .second(let b)): return a == b case (.now, .now): return true default: return false } } }
mit
S1U/True-Random
True Random/True Random/RandomInteger.swift
1
2010
// // RandomInteger.swift // True Random // // Created by Stephen on 04/10/2017. // Copyright © 2017 S1U. All rights reserved. // import Foundation import SwiftyJSON import Alamofire class RandomInteger: NSObject { private let apiURL = "https://api.random.org/json-rpc/1/invoke" private let apiKey = "2296a8df-b886-489f-91dd-cc22d3286388" var pool = [UInt]() func from(min: UInt, max: UInt, count: UInt, completionHandler: @escaping ([UInt]) ->()) { // func from(min: UInt, max: UInt, count: UInt) { let urlParams: [String : Any] = ["jsonrpc":"2.0", "method":"generateIntegers", "params": ["apiKey": apiKey, "n": count, "min": min, "max": max, "replacement":false, "base":10], "id":28610] Alamofire.request(apiURL, method: .get, parameters: urlParams, encoding: JSONEncoding.default).responseJSON { response in // if response.result.isSuccess { // let randomJSON = JSON(response.result.value!) // self.updatePool(randomJSON) // } else { // print(response.result.error!) // } switch response.result { case .success(let value): let randomNums = JSON(value)["result", "random", "data"].arrayObject as! [UInt] completionHandler(randomNums) case .failure(let error): print(error) } } } // func updatePool(_ randomJSON: JSON) { // pool = randomJSON["result"]["random"]["data"].arrayObject as! [UInt] // print("pool is \(pool)") // } }
gpl-3.0
katsana/katsana-sdk-ios
KatsanaSDK/Manager/KatsanaAPI+Address.swift
1
717
// // KatsanaAPI+Address.swift // KatsanaSDK // // Created by Wan Ahmad Lutfi on 14/10/2016. // Copyright © 2016 pixelated. All rights reserved. // import CoreLocation extension KatsanaAPI { public func requestAddress(for location:CLLocationCoordinate2D, completion: @escaping (KTAddress?) -> Void, failure: @escaping (_ error: Error?) -> Void = {_ in }) -> Void { AddressRequest.requestAddress(for: location) { (address, error) in if error != nil{ self.log.error("Error getting address from Katsana platform \(location), \(String(describing: error))") failure(error) }else{ completion(address) } } } }
apache-2.0
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Example-OSX/Common/Extensions/NSViewExtensions.swift
1
1182
import Cocoa extension NSView { static var defaultAnimationDuration: TimeInterval { return 0.2 } static var defaultAnimationTimingFunction: CAMediaTimingFunction { return CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) } static func animate(duration: TimeInterval = defaultAnimationDuration, timingFunction: CAMediaTimingFunction = defaultAnimationTimingFunction, animations: () -> Void, completion: (() -> Void)? = nil) { NSAnimationContext.runAnimationGroup({ context in context.allowsImplicitAnimation = true context.duration = duration context.timingFunction = timingFunction animations() }, completionHandler: completion) } static func animate(withDuration duration: TimeInterval = defaultAnimationDuration, timingFunction: CAMediaTimingFunction = defaultAnimationTimingFunction, animations: () -> Void) { animate(duration: duration, timingFunction: timingFunction, animations: animations, completion: nil) } }
mit
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1176-swift-constraints-constraintsystem-matchtypes.swift
13
392
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct j<d : Sequencpe> { func f<d>() -> [j<d>] { func f<e>() -> (e, e -> e) -> e { { { f } } protocol f { class func c() } class e: f { class func c } } enum A : String { case
apache-2.0
coolsamson7/inject
Inject/xml/Ancestor.swift
1
387
// // Ancestor.swift // Inject // // Created by Andreas Ernst on 18.07.16. // Copyright © 2016 Andreas Ernst. All rights reserved. // // classes implementing this protocol will be informaed about constructed child nodes public protocol Ancestor { /// informs this instance about a new child /// - Parameter chidl: any child func addChild(_ child : AnyObject) -> Void }
mit
ilyapuchka/SwiftNetworking
SwiftNetworking/NSData+Multipart.swift
1
7842
// // NSData+Multipart.swift // SwiftNetworking // // Created by Ilya Puchka on 11.09.15. // Copyright © 2015 Ilya Puchka. All rights reserved. // import Foundation public struct MultipartBodyItem: APIRequestDataEncodable, Equatable { let data: NSData let contentType: MIMEType let headers: [HTTPHeader] public init(data: NSData, contentType: MIMEType, headers: [HTTPHeader]) { self.data = data.copy() as! NSData self.contentType = contentType self.headers = headers } public init?(multipartData: NSData) { let (data, contentType, headers) = MultipartBodyItem.parseMultipartData(multipartData) guard let _ = contentType, _ = data else { return nil } self.headers = headers self.contentType = contentType! self.data = data! } static private func parseMultipartData(multipartData: NSData) -> (NSData?, MIMEType?, [HTTPHeader]) { var headers = [HTTPHeader]() var contentType: MIMEType? var data: NSData? let dataLines = MultipartBodyItem.multipartDataLines(multipartData) for dataLine in dataLines { let line = NSString(data: dataLine, encoding: NSUTF8StringEncoding)! as String if let _contentType = MultipartBodyItem.contentTypeFromLine(line) { contentType = _contentType } else if let contentLength = MultipartBodyItem.contentLengthFromLine(line) { data = MultipartBodyItem.contentDataFromData(multipartData, contentLength: contentLength) } else if let header = MultipartBodyItem.headersFromLine(line) { headers.append(header) } } return (data, contentType, headers) } static private func multipartDataLines(data: NSData) -> [NSData] { var dataLines = data.lines() dataLines.removeLast() return dataLines } private static let ContentTypePrefix = "Content-Type: " private static let ContentLengthPrefix = "Content-Length: " private static func contentTypeFromLine(line: String) -> String? { guard line.hasPrefix(MultipartBodyItem.ContentTypePrefix) else { return nil } return line.substringFromIndex(MultipartBodyItem.ContentTypePrefix.endIndex) } private static func contentLengthFromLine(line: String) -> Int? { guard line.hasPrefix(MultipartBodyItem.ContentLengthPrefix) else { return nil } let scaner = NSScanner(string: line.substringFromIndex(MultipartBodyItem.ContentLengthPrefix.endIndex)) var contentLength: Int = 0 scaner.scanInteger(&contentLength) return contentLength } private static func headersFromLine(line: String) -> HTTPHeader? { guard let colonRange = line.rangeOfString(": ") else { return nil } let key = line.substringToIndex(colonRange.startIndex) let value = line.substringFromIndex(colonRange.endIndex) return HTTPHeader.Custom(key, value) } private static func contentDataFromData(data: NSData, contentLength: Int) -> NSData { let carriageReturn = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)! let range = NSMakeRange(data.length - carriageReturn.length - contentLength, contentLength) return data.subdataWithRange(range) } } //MARK: - APIRequestDataEncodable extension MultipartBodyItem { public func encodeForAPIRequestData() throws -> NSData { return NSData() } } //MARK: - Equatable public func ==(lhs: MultipartBodyItem, rhs: MultipartBodyItem) -> Bool { return lhs.data == rhs.data && lhs.contentType == rhs.contentType && lhs.headers == rhs.headers } public func NSSubstractRange(fromRange: NSRange, _ substractRange: NSRange) -> NSRange { return NSMakeRange(NSMaxRange(substractRange), NSMaxRange(fromRange) - NSMaxRange(substractRange)); } public func NSRangeInterval(fromRange: NSRange, toRange: NSRange) -> NSRange { if (NSIntersectionRange(fromRange, toRange).length > 0) { return NSMakeRange(0, 0); } if (NSMaxRange(fromRange) < NSMaxRange(toRange)) { return NSMakeRange(NSMaxRange(fromRange), toRange.location - NSMaxRange(fromRange)); } else { return NSMakeRange(NSMaxRange(toRange), fromRange.location - NSMaxRange(toRange)); } } extension NSMutableData { public func appendString(string: String) { appendData(string.dataUsingEncoding(NSUTF8StringEncoding) ?? NSData()) } public func appendNewLine() { appendString("\r\n") } public func appendStringLine(string: String) { appendString(string) appendNewLine() } public func appendMultipartBodyItem(item: MultipartBodyItem, boundary: String) { appendStringLine("--\(boundary)") appendStringLine("Content-Type: \(item.contentType)") appendStringLine("Content-Length: \(item.data.length)") for header in item.headers { appendStringLine("\(header.key): \(header.requestHeaderValue)") } appendNewLine() appendData(item.data) appendNewLine() } } extension NSData { public convenience init(multipartDataWithItems items: [MultipartBodyItem], boundary: String) { let multipartData = NSMutableData() for item in items { multipartData.appendMultipartBodyItem(item, boundary: boundary) } multipartData.appendStringLine("--\(boundary)--") self.init(data: multipartData) } public func multipartDataItemsSeparatedWithBoundary(boundary: String) -> [MultipartBodyItem] { let boundaryData = "--\(boundary)".dataUsingEncoding(NSUTF8StringEncoding)! let trailingData = "--\r\n".dataUsingEncoding(NSUTF8StringEncoding)! let items = componentsSeparatedByData(boundaryData).flatMap { (data: NSData) -> MultipartBodyItem? in if data != trailingData { return MultipartBodyItem(multipartData: data) } return nil } return items } public func componentsSeparatedByData(boundary: NSData) -> [NSData] { var components = [NSData]() enumerateBytesByBoundary(boundary) { (dataPart, _, _) -> Void in components.append(dataPart) } return components } public func lines() -> [NSData] { return componentsSeparatedByData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) } private func enumerateBytesByBoundary(boundary: NSData, iteration: (NSData, NSRange, inout Bool) -> Void) { var boundaryRange = NSMakeRange(0, 0) var stop = false repeat { if let subRange = subRange(boundary, boundaryRange: boundaryRange) { if subRange.length > 0 { iteration(subdataWithRange(subRange), subRange, &stop) } boundaryRange = NSMakeRange(NSMaxRange(subRange), boundary.length) } else { break; } } while (!stop && NSMaxRange(boundaryRange) < length) } private func subRange(boundary: NSData, boundaryRange: NSRange) -> NSRange? { let searchRange = NSSubstractRange(NSMakeRange(0, length), boundaryRange) let nextBoundaryRange = rangeOfData(boundary, options: NSDataSearchOptions(), range: searchRange) var subRange: NSRange? if nextBoundaryRange.location != NSNotFound { subRange = NSRangeInterval(boundaryRange, toRange: nextBoundaryRange) } else if (NSMaxRange(boundaryRange) < length) { subRange = searchRange } return subRange } }
mit
lieonCX/Live
Live/Others/Lib/RITLImagePicker/Photofiles/Photo/RITLPhotoPreviewController.swift
1
1725
// // RITLPhotoPreviewController.swift // RITLImagePicker-Swift // // Created by YueWen on 2017/1/22. // Copyright © 2017年 YueWen. All rights reserved. // import UIKit import Photos /// 响应3D Touch的视图 class RITLPhotoPreviewController: UIViewController { /// 当前显示的资源对象 var showAsset : PHAsset = PHAsset() /// 展示图片的视图 lazy fileprivate var imageView : UIImageView = { let imageView = UIImageView() imageView.backgroundColor = .white imageView.contentMode = .scaleToFill imageView.layer.cornerRadius = 8.0 return imageView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. //获得资源的宽度与高度的比例 let scale = CGFloat(showAsset.pixelHeight) * 1.0 / CGFloat(showAsset.pixelWidth) preferredContentSize = CGSize(width: view.bounds.width, height: view.bounds.width * scale) //添加 view.addSubview(imageView) //约束布局 imageView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } //获取图片对象 RITLPhotoHandleManager.asset(representionIn: showAsset, size: preferredContentSize) { (image, asset) in self.imageView.image = image } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { print("\(self.self)deinit") } }
mit
cnoon/swift-compiler-crashes
crashes-duplicates/24135-swift-parser-parsedeclimport.swift
9
349
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A{func a { { { { { { { { { ( ( {:a{ { { [{ {( { {A{ { { func{ { { { ( { { { {( { { { a{ { { { {(( : ( ( { protocol{ {{ (({ {{{ { { a{ { { {: { { {{ " typealias b:a func x
mit
AlphaJian/LarsonApp
LarsonApp/LarsonApp/Class/JobDetail/WorkOrderViews/WorkOrderScrollView.swift
1
5466
// // WorkOrderScrollView.swift // LarsonApp // // Created by Perry Z Chen on 11/10/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class WorkOrderScrollView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBOutlet weak var callNumberContainer: UIView! @IBOutlet weak var callNumberContraint: NSLayoutConstraint! @IBOutlet weak var stationNumberContainer: UIView! @IBOutlet weak var stationNumberConstraint: NSLayoutConstraint! @IBOutlet weak var siteAddressContainer: UIView! @IBOutlet weak var siteAddressConstraint: NSLayoutConstraint! @IBOutlet weak var zipCodeContainer: UIView! @IBOutlet weak var zipCodeConstraint: NSLayoutConstraint! @IBOutlet weak var phoneNumberContainer: UIView! @IBOutlet weak var phoneNumberConstraint: NSLayoutConstraint! @IBOutlet weak var TechNumberContainer: UIView! @IBOutlet weak var techNumberConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var stationTitleLable: UILabel! @IBOutlet weak var stationContentLabel: UILabel! @IBOutlet weak var siteAddressLabel: UILabel! @IBOutlet weak var siteContentLabel: UILabel! @IBOutlet weak var zipContentLabel: UILabel! @IBOutlet weak var zipTitleLabel: UILabel! @IBOutlet weak var phoneNumTitleLabel: UILabel! @IBOutlet weak var phoneNumContentLabel: UILabel! @IBOutlet weak var techTitleLabel: UILabel! @IBOutlet weak var techContentLabel: UILabel! func initUI(model: AppointmentModel) { // let callNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // // callNumberView?.initUI(parameter: ("Call Number", model.telephoneNumber), labelWidth: LCDW) // let height = callNumberView?.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height // print("---> \(height), \(LCDW)") // callNumberView?.frame = CGRect(x: 0, y: 0, width: LCDW, height: height!) // self.callNumberContraint.constant = height! // // self.callNumberContainer.addSubview(callNumberView!) self.titleLabel.text = "Call Number" self.stationTitleLable.text = "Station Number" self.siteAddressLabel.text = "Site Address" self.zipTitleLabel.text = "Zip Code" self.phoneNumTitleLabel.text = "Phone Number" self.techTitleLabel.text = "Phone Number" //\(model.telephoneNumber)\(model.telephoneNumber)\(model.telephoneNumber)\(model.telephoneNumber) let callNumStr = "\(model.telephoneNumber)" as NSString let stationStr = model.stationNumber let siteAddressStr = model.customerAddress let zipStr = model.zipCode let phoneNumStr = model.telephoneNumber let techNumStr = model.techNumber let str = NSMutableAttributedString(string: (callNumStr).uppercased) str.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: 15.0), range:NSRange(location:0,length: (callNumStr).uppercased.characters.count )) self.callNumberContraint.constant = StringUtil.getAttributeString(str: str, width: LCDW - 30 ) self.contentLabel.text = callNumStr as String self.stationContentLabel.text = stationStr self.siteContentLabel.text = siteAddressStr self.zipContentLabel.text = zipStr self.phoneNumContentLabel.text = phoneNumStr self.techContentLabel.text = techNumStr // let stationNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // stationNumberView?.initUI(parameter: ("Station Number", ""), labelWidth: LCDW) // self.stationNumberContainer.addSubview(stationNumberView!) // // let siteAddressView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // siteAddressView?.initUI(parameter: ("Site Address", ""), labelWidth: LCDW) // self.siteAddressContainer.addSubview(siteAddressView!) // // let zipCodeView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // zipCodeView?.initUI(parameter: ("Zip Code", ""), labelWidth: LCDW) // self.zipCodeContainer.addSubview(zipCodeView!) // // let phoneNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // phoneNumberView?.initUI(parameter: ("Phone Number", ""), labelWidth: LCDW) // self.phoneNumberContainer.addSubview(phoneNumberView!) // // let techNumberView = Bundle.main.loadNibNamed("WorkOrderStaticView", owner: self, options: nil)?[0] as? WorkOrderStaticView // techNumberView?.initUI(parameter: ("Tech Number", ""), labelWidth: LCDW) // self.TechNumberContainer.addSubview(techNumberView!) self.layoutIfNeeded() self.setNeedsLayout() // self.contentSize = CGSize(width: (callNumberView?.frame.size.width)!, height: height) } }
apache-2.0
bluquar/emoji_keyboard
EmojiKeyboard/EmojiSelectKB/KBButton.swift
1
4124
// // KBButton.swift // EmojiKeyboard // // Created by Chris Barker on 10/2/14. // Copyright (c) 2014 Chris Barker. All rights reserved. // import UIKit class KBButton: NSObject { var parentView: UIView var layoutManager: ButtonLayoutManager var button: UIButton var image: UIImageView var container: UIView var row: Int var col: Int init(view: UIView, layoutManager: ButtonLayoutManager) { self.parentView = view self.layoutManager = layoutManager self.row = -1 self.col = -1 self.button = UIButton.buttonWithType(.System) as UIButton self.button.setTitle("", forState: .Normal) self.button.titleLabel?.font = UIFont.systemFontOfSize(14) self.button.backgroundColor = UIColor(white: 0.9, alpha: 0.5) self.button.layer.cornerRadius = 5 self.image = UIImageView() self.image.contentMode = UIViewContentMode.ScaleAspectFit self.container = UIView() super.init() } func addToLayout(row: Int, col: Int) { self.row = row self.col = col // add event listeners self.button.addTarget(self, action: "touchupinside:", forControlEvents: .TouchUpInside) self.button.addTarget(self, action: "touchup:", forControlEvents: .TouchUpOutside) self.button.addTarget(self, action: "touchdown:", forControlEvents: .TouchDown) // construct view hierarchy self.parentView.addSubview(self.container) self.container.addSubview(self.button) self.container.addSubview(self.image) // pin button to view self.button.setTranslatesAutoresizingMaskIntoConstraints(false) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .Width, relatedBy: .Equal, toItem: self.container, attribute: .Width, multiplier: 1.0, constant: -5.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .Height, relatedBy: .Equal, toItem: self.container, attribute: .Height, multiplier: 1.0, constant: -6.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.button, attribute: .CenterY, relatedBy: .Equal, toItem: self.container, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) // pin image to view self.image.setTranslatesAutoresizingMaskIntoConstraints(false) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .Width, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Width, multiplier: 1.0, constant: -7.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .CenterX, relatedBy: .Equal, toItem: self.container, attribute: .CenterX, multiplier: 1.0, constant: 0.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .Height, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Height, multiplier: 1.0, constant: -8.0)) self.parentView.addConstraint(NSLayoutConstraint(item: self.image, attribute: .CenterY, relatedBy: .Equal, toItem: self.container, attribute: .CenterY, multiplier: 1.0, constant: 0.0)) // constrain aspect ratio self.parentView.addConstraint(NSLayoutConstraint(item: self.container, attribute: .Height, relatedBy: .LessThanOrEqual, toItem: self.container, attribute: .Width, multiplier: 0.7, constant: 0.0)) } func touchup(sender: AnyObject) { self.button.backgroundColor = UIColor(white: 0.9, alpha: 0.5) self.image.alpha = 1.0 } func touchdown(sender: AnyObject) { self.button.backgroundColor = UIColor(white: 0.5, alpha: 0.5) self.image.alpha = 0.7 } func touchupinside(sender: AnyObject) { self.touchup(sender) self.layoutManager.tapped(self.row, col: self.col) } }
gpl-2.0
AnthonyMDev/AmazonS3RequestManager
Example/Tests/AmazonS3ACLTests.swift
2
12214
// // AmazonS3ACLTests.swift // AmazonS3RequestManager // // Created by Anthony Miller on 6/9/15. // Copyright (c) 2015 Anthony Miller. All rights reserved. // import Quick import Nimble import AmazonS3RequestManager class AmazonS3ACLSpec: QuickSpec { override func spec() { describe("PredefinedACL") { context(".privateReadWrite") { let acl = PredefinedACL.privateReadWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("private")) } } context(".publicReadWrite") { let acl = PredefinedACL.publicReadWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read-write")) } } context(".publicReadOnly") { let acl = PredefinedACL.publicReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("public-read")) } } context(".authenticatedReadOnly") { let acl = PredefinedACL.authenticatedReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("authenticated-read")) } } context(".bucketOwnerReadOnly") { let acl = PredefinedACL.bucketOwnerReadOnly it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-read")) } } context(".bucketOwnerFullControl") { let acl = PredefinedACL.bucketOwnerFullControl it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("bucket-owner-full-control")) } } context(".logDeliveryWrite") { let acl = PredefinedACL.logDeliveryWrite it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-acl"] expect(aclHeader).to(equal("log-delivery-write")) } } } describe("ACL Permission Grant") { describe("With Permission") { func aclWithPermission(_ permission: ACLPermission) -> ACLPermissionGrant { let grantee = ACLGrantee.authenticatedUsers return ACLPermissionGrant(permission: permission, grantee: grantee) } describe("read") { let permission = ACLPermission.read let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).toNot(beNil()) } } describe("write") { let permission = ACLPermission.write let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write"] expect(aclHeader).toNot(beNil()) } } describe("readACL") { let permission = ACLPermission.readACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read-acp"] expect(aclHeader).toNot(beNil()) } } describe("writeACL") { let permission = ACLPermission.writeACL let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-write-acp"] expect(aclHeader).toNot(beNil()) } } describe("fullControl") { let permission = ACLPermission.fullControl let acl = aclWithPermission(permission) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-full-control"] expect(aclHeader).toNot(beNil()) } } } describe("With Grantee") { func aclWithGrantee(_ grantee: ACLGrantee) -> ACLPermissionGrant { let permission = ACLPermission.read return ACLPermissionGrant(permission: permission, grantee: grantee) } describe("Grantee: Authenticated Users") { let grantee = ACLGrantee.authenticatedUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AuthenticatedUsers\"")) } } describe("Grantee: All Users") { let grantee = ACLGrantee.allUsers let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/global/AllUsers\"")) } } describe("Grantee: Log Delivery Group") { let grantee = ACLGrantee.logDeliveryGroup let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("uri=\"http://acs.amazonaws.com/groups/s3/LogDelivery\"")) } } describe("Grantee: Email") { let grantee = ACLGrantee.emailAddress("test@test.com") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("emailAddress=\"test@test.com\"")) } } describe("Grantee: User ID") { let grantee = ACLGrantee.userID("123456") let acl = aclWithGrantee(grantee) it("sets ACL request headers") { var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(equal("id=\"123456\"")) } } } describe("With Multiple Grantees") { func aclWithGrantees(_ grantees: Set<ACLGrantee>) -> ACLPermissionGrant { let permission = ACLPermission.read return ACLPermissionGrant(permission: permission, grantees: grantees) } it("sets ACL request headers") { let acl = aclWithGrantees([ ACLGrantee.emailAddress("test@test.com"), ACLGrantee.userID("123456")]) var request = URLRequest(url: URL(string: "http://www.test.com")!) acl.setACLHeaders(on: &request) let aclHeader = request.allHTTPHeaderFields?["x-amz-grant-read"] expect(aclHeader).to(contain("emailAddress=\"test@test.com\"")) expect(aclHeader).to(contain("id=\"123456\"")) expect(aclHeader).to(contain(", ")) } } } } }
mit
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Me/Chat/DataModel/VideoMessage.swift
1
512
// // VideoMessage.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/28. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit class VideoMessage: MessageModel { //: 视频本地路径 var path:String? //: 视频网络路径 var url:String? //: 视频预览图本地路径 var imagePath:String? //: 视频预览图网络路径 var imageUrl:String? override init() { super.init() type = .video } }
mit
barteljan/VISPER
VISPER-Core/Classes/ControllerProvider.swift
1
1160
// // ControllerProvider.swift // VISPER-Wireframe // // Created by bartel on 18.11.17. // import Foundation /// An instance providing a controller for an specific route pattern, routing option, /// parameter combination if it is responsible for it public protocol ControllerProvider { /// Checks if a ControllerProvider can create a controller for a RouteResult, RoutingOption combination /// /// - Parameters: /// - routeResult: The route result for which a controller is searched /// - routingOption: The routing option which describes how the created controller will be presented /// - Returns: true if it can create a controller, false otherwise func isResponsible( routeResult: RouteResult) -> Bool /// The provider return a view controller if he is responsible for /// /// - Parameters: /// - routeResult: The route result for which a controller is searched /// - routingOption: The routing option which describes how the created controller will be presented /// - Returns: a view controller func makeController( routeResult: RouteResult) throws -> UIViewController }
mit
vimeo/VimeoNetworking
Sources/Shared/Requests/Request+Video.swift
1
4223
// // Request+Video.swift // VimeoNetworkingExample-iOS // // Created by Huebner, Rob on 4/5/16. // Copyright © 2016 Vimeo. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` returning a single `VIMVideo` public typealias VideoRequest = Request<VIMVideo> /// `Request` returning an array of `VIMVideo` public typealias VideoListRequest = Request<[VIMVideo]> public extension Request { // MARK: - /** Create a `Request` to get a specific video - parameter videoURI: the video's URI - returns: a new `Request` */ static func videoRequest(forVideoURI videoURI: String) -> Request { return Request(path: videoURI) } /** Create a `Request` to get a specific VOD video - parameter vodVideoURI: the VOD video's URI - returns: a new `Request` */ static func vodVideoRequest(forVODVideoURI vodVideoURI: String) -> Request { let parameters = ["_video_override": "true"] return Request(path: vodVideoURI, parameters: parameters) } /** Create a `Request` to get the selected users for the vieo - parameter videoURI: the URI of the video - returns: a new `Request` */ static func selectedUsersRequest(forVideoURI videoURI: String) -> Request { let parameters = [String.perPageKey: 100] let path = videoURI + .selectedUsersPrivacyPath return Request(path: path, parameters: parameters) } // MARK: - Search /** Create a `Request` to search for videos - parameter query: the string query to use for the search - parameter refinements: optionally, refinement parameters to add to the search - returns: a new `Request` */ static func queryVideos(withQuery query: String, refinements: VimeoClient.RequestParametersDictionary? = nil) -> Request { var parameters = refinements ?? [:] parameters[.queryKey] = query return Request(path: .videosPath, parameters: parameters) } // MARK: - Edit Video /** Create a `Request` to update a video's metadata - parameter videoURI: the URI of the video to update - parameter parameters: the updated parameters - returns: a new `Request` */ static func patchVideoRequest(withVideoURI videoURI: String, parameters: VimeoClient.RequestParametersDictionary) -> Request { return Request(method: .patch, path: videoURI, parameters: parameters) } /** Create a `Request` to delete a video - parameter videoURI: the URI of the video to update - returns: a new `Request` */ static func deleteVideoRequest(forVideoURI videoURI: String) -> Request { return Request(method: .delete, path: videoURI) } } private extension String { // Request & response keys static let perPageKey = "per_page" static let queryKey = "query" // Paths static let selectedUsersPrivacyPath = "/privacy/users" static let videosPath = "/videos" }
mit
austinzheng/swift
test/IRGen/dependent_reabstraction.swift
12
627
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s func markUsed<T>(_ t: T) {} protocol A { associatedtype B func b(_: B) } struct X<Y> : A { // CHECK-LABEL: define internal swiftcc void @"$s23dependent_reabstraction1XVyxGAA1AA2aEP1byy1BQzFTW"(%swift.type** noalias nocapture dereferenceable({{.*}}), %T23dependent_reabstraction1XV* noalias nocapture swiftself, %swift.type* %Self, i8** %SelfWitnessTable) func b(_ b: X.Type) { let x: Any = b markUsed(b as X.Type) } } func foo<T: A>(_ x: T, _ y: T.B) { x.b(y) } let a = X<Int>() let b = X<String>() foo(a, X<Int>.self) foo(b, X<String>.self)
apache-2.0
zisko/swift
stdlib/public/core/Filter.swift
1
14053
//===--- Filter.swift -----------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence whose elements consist of the elements of some base /// sequence that also satisfy a given predicate. /// /// - Note: `s.lazy.filter { ... }`, for an arbitrary sequence `s`, /// is a `LazyFilterSequence`. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyFilterSequence<Base: Sequence> { @_versioned // FIXME(sil-serialize-all) internal var _base: Base /// The predicate used to determine which elements produced by /// `base` are also produced by `self`. @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance consisting of the elements `x` of `base` for /// which `isIncluded(x) == true`. @_inlineable // FIXME(sil-serialize-all) public // @testable init(_base base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = base self._predicate = isIncluded } } extension LazyFilterSequence { /// An iterator over the elements traversed by some base iterator that also /// satisfy a given predicate. /// /// - Note: This is the associated `Iterator` of `LazyFilterSequence` /// and `LazyFilterCollection`. @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { /// The underlying iterator whose elements are being filtered. public var base: Base.Iterator { return _base } @_versioned // FIXME(sil-serialize-all) internal var _base: Base.Iterator @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance that produces the elements `x` of `base` /// for which `isIncluded(x) == true`. @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal init(_base: Base.Iterator, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = _base self._predicate = isIncluded } } } extension LazyFilterSequence.Iterator: IteratorProtocol, Sequence { public typealias Element = Base.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @_inlineable // FIXME(sil-serialize-all) public mutating func next() -> Element? { while let n = _base.next() { if _predicate(n) { return n } } return nil } } extension LazyFilterSequence: LazySequenceProtocol { public typealias Element = Base.Element /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _predicate) } @_inlineable public func _customContainsEquatableElement(_ element: Element) -> Bool? { // optimization to check the element first matches the predicate guard _predicate(element) else { return false } return _base._customContainsEquatableElement(element) } } /// A lazy `Collection` wrapper that includes the elements of an /// underlying collection that satisfy a predicate. /// /// - Note: The performance of accessing `startIndex`, `first`, any methods /// that depend on `startIndex`, or of advancing an index depends /// on how sparsely the filtering predicate is satisfied, and may not offer /// the usual performance given by `Collection`. Be aware, therefore, that /// general operations on `LazyFilterCollection` instances may not have the /// documented complexity. @_fixed_layout // FIXME(sil-serialize-all) public struct LazyFilterCollection<Base : Collection> { @_versioned // FIXME(sil-serialize-all) internal var _base: Base @_versioned // FIXME(sil-serialize-all) internal let _predicate: (Base.Element) -> Bool /// Creates an instance containing the elements of `base` that /// satisfy `isIncluded`. @_inlineable // FIXME(sil-serialize-all) public // @testable init(_base: Base, _ isIncluded: @escaping (Base.Element) -> Bool) { self._base = _base self._predicate = isIncluded } } extension LazyFilterCollection : LazySequenceProtocol { public typealias Element = Base.Element public typealias Iterator = LazyFilterSequence<Base>.Iterator public typealias SubSequence = LazyFilterCollection<Base.SubSequence> // Any estimate of the number of elements that pass `_predicate` requires // iterating the collection and evaluating each element, which can be costly, // is unexpected, and usually doesn't pay for itself in saving time through // preventing intermediate reallocations. (SR-4164) @_inlineable // FIXME(sil-serialize-all) public var underestimatedCount: Int { return 0 } @_inlineable // FIXME(sil-serialize-all) public func _copyToContiguousArray() -> ContiguousArray<Base.Element> { // The default implementation of `_copyToContiguousArray` queries the // `count` property, which evaluates `_predicate` for every element -- // see the note above `underestimatedCount`. Here we treat `self` as a // sequence and only rely on underestimated count. return _copySequenceToContiguousArray(self) } /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @_inlineable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _predicate) } @_inlineable public func _customContainsEquatableElement(_ element: Element) -> Bool? { guard _predicate(element) else { return false } return _base._customContainsEquatableElement(element) } } extension LazyFilterCollection : LazyCollectionProtocol { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Base.Index /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. /// /// - Complexity: O(*n*), where *n* is the ratio between unfiltered and /// filtered collection counts. @_inlineable // FIXME(sil-serialize-all) public var startIndex: Index { var index = _base.startIndex while index != _base.endIndex && !_predicate(_base[index]) { _base.formIndex(after: &index) } return index } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @_inlineable // FIXME(sil-serialize-all) public var endIndex: Index { return _base.endIndex } // TODO: swift-3-indexing-model - add docs @_inlineable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { var i = i formIndex(after: &i) return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(after i: inout Index) { // TODO: swift-3-indexing-model: _failEarlyRangeCheck i? var index = i _precondition(index != _base.endIndex, "Can't advance past endIndex") repeat { _base.formIndex(after: &index) } while index != _base.endIndex && !_predicate(_base[index]) i = index } @inline(__always) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _advanceIndex(_ i: inout Index, step: Int) { repeat { _base.formIndex(&i, offsetBy: step) } while i != _base.endIndex && !_predicate(_base[i]) } @inline(__always) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _ensureBidirectional(step: Int) { // FIXME: This seems to be the best way of checking whether _base is // forward only without adding an extra protocol requirement. // index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return // nil when the resulting index lands outside the collection boundaries, // and therefore likely does not trap in these cases. if step < 0 { _ = _base.index( _base.endIndex, offsetBy: step, limitedBy: _base.startIndex) } } @_inlineable // FIXME(sil-serialize-all) public func distance(from start: Index, to end: Index) -> Int { // The following line makes sure that distance(from:to:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. _ = _base.distance(from: start, to: end) var _start: Index let _end: Index let step: Int if start > end { _start = end _end = start step = -1 } else { _start = start _end = end step = 1 } var count = 0 while _start != _end { count += step formIndex(after: &_start) } return count } @_inlineable // FIXME(sil-serialize-all) public func index(_ i: Index, offsetBy n: Int) -> Index { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(numericCast(n)) { _advanceIndex(&i, step: step) } return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(_ i: inout Index, offsetBy n: Int) { i = index(i, offsetBy: n) } @_inlineable // FIXME(sil-serialize-all) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:limitedBy:) is // invoked on the _base at least once, to trigger a _precondition in // forward only collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(numericCast(n)) { if i == limit { return nil } _advanceIndex(&i, step: step) } return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex( _ i: inout Index, offsetBy n: Int, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @_inlineable // FIXME(sil-serialize-all) public subscript(position: Index) -> Element { return _base[position] } @_inlineable // FIXME(sil-serialize-all) public subscript(bounds: Range<Index>) -> SubSequence { return SubSequence(_base: _base[bounds], _predicate) } } extension LazyFilterCollection : BidirectionalCollection where Base : BidirectionalCollection { @_inlineable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { var i = i formIndex(before: &i) return i } @_inlineable // FIXME(sil-serialize-all) public func formIndex(before i: inout Index) { // TODO: swift-3-indexing-model: _failEarlyRangeCheck i? var index = i _precondition(index != _base.startIndex, "Can't retreat before startIndex") repeat { _base.formIndex(before: &index) } while !_predicate(_base[index]) i = index } } extension LazySequenceProtocol { /// Returns the elements of `self` that satisfy `isIncluded`. /// /// - Note: The elements of the result are computed on-demand, as /// the result is used. No buffering storage is allocated and each /// traversal step invokes `predicate` on one or more underlying /// elements. @_inlineable // FIXME(sil-serialize-all) public func filter( _ isIncluded: @escaping (Elements.Element) -> Bool ) -> LazyFilterSequence<Self.Elements> { return LazyFilterSequence(_base: self.elements, isIncluded) } } extension LazyCollectionProtocol { /// Returns the elements of `self` that satisfy `predicate`. /// /// - Note: The elements of the result are computed on-demand, as /// the result is used. No buffering storage is allocated and each /// traversal step invokes `predicate` on one or more underlying /// elements. @_inlineable // FIXME(sil-serialize-all) public func filter( _ isIncluded: @escaping (Elements.Element) -> Bool ) -> LazyFilterCollection<Self.Elements> { return LazyFilterCollection(_base: self.elements, isIncluded) } } extension LazyFilterSequence { public func filter( _ isIncluded: @escaping (Element) -> Bool ) -> LazyFilterSequence<Base> { return LazyFilterSequence(_base: _base) { isIncluded($0) && self._predicate($0) } } } extension LazyFilterCollection { public func filter( _ isIncluded: @escaping (Element) -> Bool ) -> LazyFilterCollection<Base> { return LazyFilterCollection(_base: _base) { isIncluded($0) && self._predicate($0) } } } // @available(*, deprecated, renamed: "LazyFilterSequence.Iterator") public typealias LazyFilterIterator<T: Sequence> = LazyFilterSequence<T>.Iterator // @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use Base.Index") public typealias LazyFilterIndex<Base: Collection> = Base.Index @available(*, deprecated, renamed: "LazyFilterCollection") public typealias LazyFilterBidirectionalCollection<T> = LazyFilterCollection<T> where T : BidirectionalCollection
apache-2.0
MartinLasek/vaporberlinBE
Sources/App/Backend/Helper.swift
1
601
final class Helper { static func validateEmail(_ email: String) -> Bool { /// email must at least have 6 characters e.g: a@b.cd let minLength = 6 if email.range(of: "@") == nil || email.range(of: ".") == nil || email.count < minLength { return false } return true } static func validatePassword(_ password: String) -> Bool { let minLength = 8 return password.count >= minLength } static func errorJson(status: Int, message: String) throws -> JSON { return try JSON(node: ["status": status, "message": message]) } }
mit
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/RoomManagerDelegate.swift
2
1429
// // RoomManagerDelegate.swift // uoat // // Created by Pyro User on 18/7/16. // Copyright © 2016 Zed. All rights reserved. // import Foundation protocol RoomManagerDelegate:class { func roomManagerDidFinish(broker:RoomManager); func roomManager(broker:RoomManager, didAddLocalStream localStream:RTCMediaStream); func roomManager(broker:RoomManager, didRemoveLocalStream localStream:RTCMediaStream); func roomManager(broker:RoomManager, didAddStream remoteStream:RTCMediaStream, ofPeer remotePeer:NBMPeer); func roomManager(broker:RoomManager, didRemoveStream remoteStream:RTCMediaStream, ofPeer remotePeer:NBMPeer); func roomManager(broker:RoomManager, peerJoined peer:NBMPeer); func roomManager(broker:RoomManager, peerLeft peer:NBMPeer); func roomManager(broker:RoomManager, peerEvicted peer:NBMPeer); func roomManager(broker:RoomManager, roomJoined error:NSError?); func roomManager(broker:RoomManager, messageReceived message:String, ofPeer peer:NBMPeer); func roomManagerPeerStatusChanged(broker:RoomManager); func roomManager(broker:RoomManager, didFailWithError error:NSError); func roomManager(broker:RoomManager, iceStatusChanged state:RTCIceConnectionState, ofPeer peer:NBMPeer); func roomManager(broker:RoomManager, didSentCustomRequest error:NSError, didResponse response:NBMResponse); }
apache-2.0
jmgc/swift
test/IRGen/builtins.swift
1
36474
// RUN: %target-swift-frontend -module-name builtins -parse-stdlib -disable-access-control -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime // REQUIRES: CPU=x86_64 import Swift // CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type // CHECK-DAG: [[X:%T8builtins1XC]] = type // CHECK-DAG: [[Y:%T8builtins1YC]] = type typealias Int = Builtin.Int32 typealias Bool = Builtin.Int1 // CHECK: call swiftcc void @swift_errorInMain( infix operator * infix operator / infix operator % infix operator + infix operator - infix operator << infix operator >> infix operator ... infix operator < infix operator <= infix operator > infix operator >= infix operator == infix operator != func * (lhs: Int, rhs: Int) -> Int { return Builtin.mul_Int32(lhs, rhs) // CHECK: mul i32 } func / (lhs: Int, rhs: Int) -> Int { return Builtin.sdiv_Int32(lhs, rhs) // CHECK: sdiv i32 } func % (lhs: Int, rhs: Int) -> Int { return Builtin.srem_Int32(lhs, rhs) // CHECK: srem i32 } func + (lhs: Int, rhs: Int) -> Int { return Builtin.add_Int32(lhs, rhs) // CHECK: add i32 } func - (lhs: Int, rhs: Int) -> Int { return Builtin.sub_Int32(lhs, rhs) // CHECK: sub i32 } // In C, 180 is <<, >> func < (lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_slt_Int32(lhs, rhs) // CHECK: icmp slt i32 } func > (lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sgt_Int32(lhs, rhs) // CHECK: icmp sgt i32 } func <=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sle_Int32(lhs, rhs) // CHECK: icmp sle i32 } func >=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_sge_Int32(lhs, rhs) // CHECK: icmp sge i32 } func ==(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_eq_Int32(lhs, rhs) // CHECK: icmp eq i32 } func !=(lhs: Int, rhs: Int) -> Bool { return Builtin.cmp_ne_Int32(lhs, rhs) // CHECK: icmp ne i32 } func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64) -> Builtin.RawPointer { return Builtin.gepRaw_Int64(ptr, offset) // CHECK: getelementptr inbounds i8, i8* } // CHECK: define hidden {{.*}}i64 @"$s8builtins9load_test{{[_0-9a-zA-Z]*}}F" func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64* // CHECK-NEXT: load i64, i64* [[CASTPTR]] // CHECK: ret return Builtin.load(ptr) } // CHECK: define hidden {{.*}}i64 @"$s8builtins13load_raw_test{{[_0-9a-zA-Z]*}}F" func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64* // CHECK-NEXT: load i64, i64* [[CASTPTR]] // CHECK: ret return Builtin.loadRaw(ptr) } // CHECK: define hidden {{.*}}void @"$s8builtins11assign_test{{[_0-9a-zA-Z]*}}F" func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) { Builtin.assign(value, ptr) // CHECK: ret } // CHECK: define hidden {{.*}}%swift.refcounted* @"$s8builtins16load_object_test{{[_0-9a-zA-Z]*}}F" func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]** // CHECK: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[T0]]) // CHECK: ret [[REFCOUNT]]* [[T0]] return Builtin.load(ptr) } // CHECK: define hidden {{.*}}%swift.refcounted* @"$s8builtins20load_raw_object_test{{[_0-9a-zA-Z]*}}F" func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]** // CHECK: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[T0]]) // CHECK: ret [[REFCOUNT]]* [[T0]] return Builtin.loadRaw(ptr) } // CHECK: define hidden {{.*}}void @"$s8builtins18assign_object_test{{[_0-9a-zA-Z]*}}F" func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) { Builtin.assign(value, ptr) } // CHECK: define hidden {{.*}}void @"$s8builtins16init_object_test{{[_0-9a-zA-Z]*}}F" func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) { // CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to [[REFCOUNT]]** // CHECK-NEXT: call [[REFCOUNT]]* @swift_retain([[REFCOUNT]]* returned [[SRC:%.*]]) // CHECK-NEXT: store [[REFCOUNT]]* [[SRC]], [[REFCOUNT]]** [[DEST]] Builtin.initialize(value, ptr) } func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8, i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32, d: inout Builtin.FPIEEE64 ) { // CHECK: cast_test i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast } func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) { i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32( i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16( var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16( Builtin.int_trap() // CHECK: llvm.trap() } // CHECK: define hidden {{.*}}void @"$s8builtins19sizeof_alignof_testyyF"() func sizeof_alignof_test() { // CHECK: store i64 4, i64* var xs = Builtin.sizeof(Int.self) // CHECK: store i64 4, i64* var xa = Builtin.alignof(Int.self) // CHECK: store i64 1, i64* var ys = Builtin.sizeof(Bool.self) // CHECK: store i64 1, i64* var ya = Builtin.alignof(Bool.self) } // CHECK: define hidden {{.*}}void @"$s8builtins27generic_sizeof_alignof_testyyxlF" func generic_sizeof_alignof_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[T:%.*]], i32 0, i32 8 // CHECK-NEXT: [[SIZE:%.*]] = load i64, i64* [[T0]] // CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]] var s = Builtin.sizeof(T.self) // CHECK: [[T0:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[T:%.*]], i32 0, i32 10 // CHECK-NEXT: [[FLAGS:%.*]] = load i32, i32* [[T0]] // CHECK-NEXT: [[T2:%.*]] = zext i32 [[FLAGS]] to i64 // CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 255 // CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1 // CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]] var a = Builtin.alignof(T.self) } // CHECK: define hidden {{.*}}void @"$s8builtins21generic_strideof_testyyxlF" func generic_strideof_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[T:%.*]], i32 9 // CHECK-NEXT: [[STRIDE:%.*]] = load i64, i64* [[T0]] // CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]] var s = Builtin.strideof(T.self) } class X {} class Y {} func move(_ ptr: Builtin.RawPointer) { var temp : Y = Builtin.take(ptr) // CHECK: define hidden {{.*}}void @"$s8builtins4move{{[_0-9a-zA-Z]*}}F" // CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]** // CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]] // CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}} } func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) { var ptr = Builtin.allocRaw(size, align) Builtin.deallocRaw(ptr, size, align) } func fence_test() { // CHECK: fence acquire Builtin.fence_acquire() // CHECK: fence syncscope("singlethread") acq_rel Builtin.fence_acqrel_singlethread() } func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) { // rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers // CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire // CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0 // CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1 // CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4 // CHECK: [[Z_SUCCESS_B:%.*]] = zext i1 [[Z_SUCCESS]] to i8 // CHECK: store i8 [[Z_SUCCESS_B]], i8* {{.*}}, align 1 var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b) // CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic // CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0 // CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1 // CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4 // CHECK: [[Y_SUCCESS_B:%.*]] = zext i1 [[Y_SUCCESS]] to i8 // CHECK: store i8 [[Y_SUCCESS_B]], i8* {{.*}}, align 1 var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b) // CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} syncscope("singlethread") acquire monotonic // CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0 // CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1 // CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4 // CHECK: [[X_SUCCESS_B:%.*]] = zext i1 [[X_SUCCESS]] to i8 // CHECK: store i8 [[X_SUCCESS_B]], i8* {{.*}}, align 1 var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b) // CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst // CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0 // CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1 // CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8* // CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8 // CHECK: [[W_SUCCESS_B:%.*]] = zext i1 [[W_SUCCESS]] to i8 // CHECK: store i8 [[W_SUCCESS_B]], i8* {{.*}}, align 1 var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr) // CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst // CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0 // CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1 // CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8* // CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8 // CHECK: [[V_SUCCESS_B:%.*]] = zext i1 [[V_SUCCESS]] to i8 // CHECK: store i8 [[V_SUCCESS_B]], i8* {{.*}}, align 1 var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr) } func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, ptr2: Builtin.RawPointer) { // CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a) // CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a) // CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} syncscope("singlethread") acquire var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a) // rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers // CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} syncscope("singlethread") acquire var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2) } func addressof_test(_ a: inout Int, b: inout Bool) { // CHECK: bitcast i32* {{.*}} to i8* var ap : Builtin.RawPointer = Builtin.addressof(&a) // CHECK: bitcast i1* {{.*}} to i8* var bp : Builtin.RawPointer = Builtin.addressof(&b) } func fneg_test(_ half: Builtin.FPIEEE16, single: Builtin.FPIEEE32, double: Builtin.FPIEEE64) -> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64) { // CHECK: fsub half 0xH8000, {{%.*}} // CHECK: fsub float -0.000000e+00, {{%.*}} // CHECK: fsub double -0.000000e+00, {{%.*}} return (Builtin.fneg_FPIEEE16(half), Builtin.fneg_FPIEEE32(single), Builtin.fneg_FPIEEE64(double)) } // The call to the builtins should get removed before we reach IRGen. func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () { Builtin.staticReport(b, b, ptr); return Builtin.staticReport(b, b, ptr); } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins12testCondFail{{[_0-9a-zA-Z]*}}F"(i1 %0, i1 %1) func testCondFail(_ b: Bool, c: Bool) { // CHECK: [[EXPECT:%.*]] = call i1 @llvm.expect.i1(i1 %0, i1 false) // CHECK: br i1 [[EXPECT]], label %[[FAIL:.*]], label %[[CONT:.*]] Builtin.condfail_message(b, StaticString("message").unsafeRawPointer) // CHECK: [[CONT]] // CHECK: [[EXPECT:%.*]] = call i1 @llvm.expect.i1(i1 %1, i1 false) // CHECK: br i1 [[EXPECT]], label %[[FAIL2:.*]], label %[[CONT:.*]] Builtin.condfail_message(c, StaticString("message").unsafeRawPointer) // CHECK: [[CONT]]: // CHECK: ret void // CHECK: [[FAIL]]: // CHECK: call void @llvm.trap() // CHECK: unreachable // CHECK: [[FAIL2]]: // CHECK: call void @llvm.trap() // CHECK: unreachable } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins8testOnce{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1) {{.*}} { // CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]* // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: [[IS_DONE_X:%.*]] = call i1 @llvm.expect.i1(i1 [[IS_DONE]], i1 true) // CHECK-objc: br i1 [[IS_DONE_X]], label %[[DONE:.*]], label %[[NOT_DONE:.*]] // CHECK-objc: [[DONE]]: // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]]) // CHECK-objc: [[NOT_DONE]]: // CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* undef) // CHECK-objc: br label %[[DONE]] func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(c) () -> ()) { Builtin.once(p, f) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins19testOnceWithContext{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1, i8* %2) {{.*}} { // CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]* // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: [[IS_DONE_X:%.*]] = call i1 @llvm.expect.i1(i1 [[IS_DONE]], i1 true) // CHECK-objc: br i1 [[IS_DONE_X]], label %[[DONE:.*]], label %[[NOT_DONE:.*]] // CHECK-objc: [[DONE]]: // CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]] // CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1 // CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]]) // CHECK-objc: [[NOT_DONE]]: // CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* %2) // CHECK-objc: br label %[[DONE]] func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(c) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) { Builtin.onceWithContext(p, f, k) } class C {} struct S {} #if _runtime(_ObjC) @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} #endif protocol P {} // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins10canBeClass{{[_0-9a-zA-Z]*}}F" func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) { #if _runtime(_ObjC) // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(O.self)) // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(OP1.self)) typealias ObjCCompo = OP1 & OP2 // CHECK-objc: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(ObjCCompo.self)) #endif // CHECK: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(S.self)) // CHECK: call {{.*}}void {{%.*}}(i8 1 f(Builtin.canBeClass(C.self)) // CHECK: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(P.self)) #if _runtime(_ObjC) typealias MixedCompo = OP1 & P // CHECK-objc: call {{.*}}void {{%.*}}(i8 0 f(Builtin.canBeClass(MixedCompo.self)) #endif // CHECK: call {{.*}}void {{%.*}}(i8 2 f(Builtin.canBeClass(T.self)) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins15destroyPODArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i64 %1) // CHECK-NOT: loop: // CHECK: ret void func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) { Builtin.destroyArray(Int.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins18destroyNonPODArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i64 %1) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayDestroy( func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) { Builtin.destroyArray(C.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins15destroyGenArray_5count_yBp_BwxtlF"(i8* %0, i64 %1, %swift.opaque* noalias nocapture %2, %swift.type* %T) // CHECK-NOT: loop: // CHECK: call void @swift_arrayDestroy func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) { Builtin.destroyArray(T.self, array, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins12copyPODArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1, i64 %2) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) // check: mul nuw i64 4, %2 // check: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false) func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(Int.self, dest, src, count) Builtin.takeArrayFrontToBack(Int.self, dest, src, count) Builtin.takeArrayBackToFront(Int.self, dest, src, count) Builtin.assignCopyArrayNoAlias(Int.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(Int.self, dest, src, count) Builtin.assignCopyArrayBackToFront(Int.self, dest, src, count) Builtin.assignTakeArray(Int.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins11copyBTArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1, i64 %2) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy // CHECK: mul nuw i64 8, %2 // CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i1 false) // CHECK: mul nuw i64 8, %2 // CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i1 false) // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(C.self, dest, src, count) Builtin.takeArrayFrontToBack(C.self, dest, src, count) Builtin.takeArrayBackToFront(C.self, dest, src, count) Builtin.assignCopyArrayNoAlias(C.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(C.self, dest, src, count) Builtin.assignCopyArrayBackToFront(C.self, dest, src, count) Builtin.assignTakeArray(C.self, dest, src, count) } struct W { weak var c: C? } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins15copyNonPODArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1, i64 %2) {{.*}} { // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy( // CHECK-NOT: loop{{.*}}: // CHECK: call void @swift_arrayInitWithTakeFrontToBack( // CHECK-NOT: loop{{.*}}: // CHECK: call void @swift_arrayInitWithTakeBackToFront( // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) { Builtin.copyArray(W.self, dest, src, count) Builtin.takeArrayFrontToBack(W.self, dest, src, count) Builtin.takeArrayBackToFront(W.self, dest, src, count) Builtin.assignCopyArrayNoAlias(W.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(W.self, dest, src, count) Builtin.assignCopyArrayBackToFront(W.self, dest, src, count) Builtin.assignTakeArray(W.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins12copyGenArray{{[_0-9a-zA-Z]*}}F"(i8* %0, i8* %1, i64 %2, %swift.opaque* noalias nocapture %3, %swift.type* %T) // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithCopy // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithTakeFrontToBack( // CHECK-NOT: loop: // CHECK: call void @swift_arrayInitWithTakeBackToFront( // CHECK: call void @swift_arrayAssignWithCopyNoAlias( // CHECK: call void @swift_arrayAssignWithCopyFrontToBack( // CHECK: call void @swift_arrayAssignWithCopyBackToFront( // CHECK: call void @swift_arrayAssignWithTake( func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) { Builtin.copyArray(T.self, dest, src, count) Builtin.takeArrayFrontToBack(T.self, dest, src, count) Builtin.takeArrayBackToFront(T.self, dest, src, count) Builtin.assignCopyArrayNoAlias(T.self, dest, src, count) Builtin.assignCopyArrayFrontToBack(T.self, dest, src, count) Builtin.assignCopyArrayBackToFront(T.self, dest, src, count) Builtin.assignTakeArray(T.self, dest, src, count) } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins24conditionallyUnreachableyyF" // CHECK-NEXT: entry // CHECK-NEXT: unreachable func conditionallyUnreachable() { Builtin.conditionallyUnreachable() } struct Abc { var value : Builtin.Word } // CHECK-LABEL: define hidden {{.*}}@"$s8builtins22assumeNonNegative_testyBwAA3AbcVzF" func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word { // CHECK: load {{.*}}, !range ![[R:[0-9]+]] return Builtin.assumeNonNegative_Word(x.value) } @inline(never) func return_word(_ x: Builtin.Word) -> Builtin.Word { return x } // CHECK-LABEL: define hidden {{.*}}@"$s8builtins23assumeNonNegative_test2yBwBwF" func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word { // CHECK: call {{.*}}, !range ![[R]] return Builtin.assumeNonNegative_Word(return_word(x)) } struct Empty {} struct Pair { var i: Int, b: Bool } // CHECK-LABEL: define hidden {{.*}}i64 @"$s8builtins15zeroInitializerAA5EmptyV_AA4PairVtyF"() {{.*}} { // CHECK: [[ALLOCA:%.*]] = alloca { i64 } // CHECK: bitcast // CHECK: lifetime.start // CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]] // CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0 // CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0 // CHECK: store i32 0, i32* [[FLDI]] // CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1 // CHECK: [[BYTE_ADDR:%.*]] = bitcast i1* [[FLDB]] to i8* // CHECK: store i8 0, i8* [[BYTE_ADDR]] // CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0 // CHECK: [[RES:%.*]] = load i64, i64* [[RET]] // CHECK: ret i64 [[RES]] func zeroInitializer() -> (Empty, Pair) { return (Builtin.zeroInitializer(), Builtin.zeroInitializer()) } // CHECK-LABEL: define hidden {{.*}}i64 @"$s8builtins20zeroInitializerTupleAA5EmptyV_AA4PairVtyF"() {{.*}} { // CHECK: [[ALLOCA:%.*]] = alloca { i64 } // CHECK: bitcast // CHECK: lifetime.start // CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]] // CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0 // CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0 // CHECK: store i32 0, i32* [[FLDI]] // CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1 // CHECK: [[BYTE_ADDR:%.*]] = bitcast i1* [[FLDB]] to i8* // CHECK: store i8 0, i8* [[BYTE_ADDR]] // CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0 // CHECK: [[RES:%.*]] = load i64, i64* [[RET]] // CHECK: ret i64 [[RES]] func zeroInitializerTuple() -> (Empty, Pair) { return Builtin.zeroInitializer() } // CHECK-LABEL: define hidden {{.*}}void @"$s8builtins20zeroInitializerEmptyyyF"() {{.*}} { // CHECK: ret void func zeroInitializerEmpty() { return Builtin.zeroInitializer() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // CHECK: define hidden {{.*}}void @"$s8builtins26acceptsBuiltinNativeObjectyyBoSgzF"([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}}) %0) {{.*}} { func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {} // native // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins8isUniqueyBi1_BoSgzF"({{%.*}}* nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted** // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2) // CHECK-NEXT: ret i1 %3 func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return Builtin.isUnique(&ref) } // native nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins8isUniqueyBi1_BozF"(%swift.refcounted** nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1) // CHECK-NEXT: ret i1 %2 func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return Builtin.isUnique(&ref) } // CHECK: define hidden {{.*}}void @"$s8builtins16acceptsAnyObjectyyyXlSgzF"([[OPTIONAL_ANYOBJECT_TY:%.*]]* nocapture dereferenceable({{.*}}) %0) {{.*}} { func acceptsAnyObject(_ ref: inout Builtin.AnyObject?) {} // ObjC // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins8isUniqueyBi1_yXlSgzF"({{%.*}}* nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: [[ADDR:%.+]] = getelementptr inbounds [[OPTIONAL_ANYOBJECT_TY]], [[OPTIONAL_ANYOBJECT_TY]]* %0, i32 0, i32 0 // CHECK-NEXT: [[CASTED:%.+]] = bitcast {{.+}}* [[ADDR]] to [[UNKNOWN_OBJECT:%objc_object|%swift\.refcounted]]** // CHECK-NEXT: [[REF:%.+]] = load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** [[CASTED]] // CHECK-objc-NEXT: [[RESULT:%.+]] = call i1 @swift_isUniquelyReferencedNonObjC([[UNKNOWN_OBJECT]]* [[REF]]) // CHECK-native-NEXT: [[RESULT:%.+]] = call i1 @swift_isUniquelyReferenced_native([[UNKNOWN_OBJECT]]* [[REF]]) // CHECK-NEXT: ret i1 [[RESULT]] func isUnique(_ ref: inout Builtin.AnyObject?) -> Bool { return Builtin.isUnique(&ref) } // ObjC nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins8isUniqueyBi1_yXlzF" // CHECK-SAME: (%AnyObject* nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: [[ADDR:%.+]] = getelementptr inbounds %AnyObject, %AnyObject* %0, i32 0, i32 0 // CHECK-NEXT: [[REF:%.+]] = load [[UNKNOWN_OBJECT]]*, [[UNKNOWN_OBJECT]]** [[ADDR]] // CHECK-objc-NEXT: [[RESULT:%.+]] = call i1 @swift_isUniquelyReferencedNonObjC_nonNull([[UNKNOWN_OBJECT]]* [[REF]]) // CHECK-native-NEXT: [[RESULT:%.+]] = call i1 @swift_isUniquelyReferenced_nonNull_native([[UNKNOWN_OBJECT]]* [[REF]]) // CHECK-NEXT: ret i1 [[RESULT]] func isUnique(_ ref: inout Builtin.AnyObject) -> Bool { return Builtin.isUnique(&ref) } // BridgeObject nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins8isUniqueyBi1_BbzF"(%swift.bridge** nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0 // CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1) // CHECK-NEXT: ret i1 %2 func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return Builtin.isUnique(&ref) } // CHECK-LABEL: define hidden{{.*}} @"$s8builtins10assumeTrueyyBi1_F" // CHECK: call void @llvm.assume(i1 %0) // CHECK: ret func assumeTrue(_ x: Builtin.Int1) { Builtin.assume_Int1(x) } // BridgeObject nonNull // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins15isUnique_nativeyBi1_BbzF"(%swift.bridge** nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted** // CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1 // CHECK-NEXT: call i1 @swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2) // CHECK-NEXT: ret i1 %3 func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return Builtin.isUnique_native(&ref) } // ImplicitlyUnwrappedOptional argument to isUnique. // CHECK-LABEL: define hidden {{.*}}i1 @"$s8builtins11isUniqueIUOyBi1_BoSgzF"(%{{.*}}* nocapture dereferenceable({{.*}}) %0) {{.*}} { // CHECK-NEXT: entry: // CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* // CHECK: ret i1 func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool { var iuo : Builtin.NativeObject! = ref return Builtin.isUnique(&iuo) } // CHECK-LABEL: define hidden {{.*}} @"$s8builtins19COWBufferForReadingyAA1CCADnF" // CHECK: ret %T8builtins1CC* %0 func COWBufferForReading(_ ref: __owned C) -> C { return Builtin.COWBufferForReading(ref) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test func generic_ispod_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[T:%.*]], i32 10 // CHECK-NEXT: [[FLAGS:%.*]] = load i32, i32* [[T0]] // CHECK-NEXT: [[ISNOTPOD:%.*]] = and i32 [[FLAGS]], 65536 // CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i32 [[ISNOTPOD]], 0 // CHECK-NEXT: [[BYTE_ADDR:%.*]] = bitcast i1* [[S:%.*]] to i8* // CHECK-NEXT: [[BYTE:%.*]] = zext i1 [[ISPOD]] to i8 // CHECK-NEXT: store i8 [[BYTE]], i8* [[BYTE_ADDR]] var s = Builtin.ispod(T.self) } // CHECK-LABEL: define {{.*}} @{{.*}}ispod_test func ispod_test() { // CHECK: store i8 1, i8* // CHECK: store i8 0, i8* var t = Builtin.ispod(Int.self) var f = Builtin.ispod(Builtin.NativeObject.self) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_isbitwisetakable_test func generic_isbitwisetakable_test<T>(_: T) { // CHECK: [[T0:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[T:%.*]], i32 10 // CHECK-NEXT: [[FLAGS:%.*]] = load i32, i32* [[T0]] // CHECK-NEXT: [[ISNOTBITWISETAKABLE:%.*]] = and i32 [[FLAGS]], 1048576 // CHECK-NEXT: [[ISBITWISETAKABLE:%.*]] = icmp eq i32 [[ISNOTBITWISETAKABLE]], 0 // CHECK-NEXT: [[BYTE_ADDR:%.*]] = bitcast i1* [[S:%.*]] // CHECK-NEXT: [[BYTE:%.*]] = zext i1 [[ISBITWISETAKABLE]] to i8 // CHECK-NEXT: store i8 [[BYTE]], i8* [[BYTE_ADDR]] var s = Builtin.isbitwisetakable(T.self) } // CHECK-LABEL: define {{.*}} @{{.*}}isbitwisetakable_test func isbitwisetakable_test() { // CHECK: store i8 1, i8* // CHECK: store i8 1, i8* // CHECK: store i8 1, i8* // CHECK: store i8 1, i8* // CHECK: store i8 0, i8* var t1 = Builtin.isbitwisetakable(Int.self) var t2 = Builtin.isbitwisetakable(C.self) var t3 = Builtin.isbitwisetakable(Abc.self) var t4 = Builtin.isbitwisetakable(Empty.self) var f = Builtin.isbitwisetakable(W.self) } // CHECK-LABEL: define {{.*}} @{{.*}}is_same_metatype func is_same_metatype_test(_ t1: Any.Type, _ t2: Any.Type) { // CHECK: [[MT1_AS_PTR:%.*]] = bitcast %swift.type* %0 to i8* // CHECK: [[MT2_AS_PTR:%.*]] = bitcast %swift.type* %1 to i8* // CHECK: icmp eq i8* [[MT1_AS_PTR]], [[MT2_AS_PTR]] var t = Builtin.is_same_metatype(t1, t2) } // CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test // CHECK: call {{.*}}* @{{.*}}swift_{{.*}}etain({{.*}}* returned %0) // CHECK: ret {{.*}}* %0 func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T { let (g, _) = Builtin.unsafeGuaranteed(t) return g } // CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test // CHECK: [[LOCAL1:%.*]] = alloca %swift.refcounted* // CHECK: [[LOCAL2:%.*]] = alloca %swift.refcounted* // CHECK: call %swift.refcounted* @swift_retain(%swift.refcounted* returned %0) // CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL2]] // CHECK-NOT: call void @swift_release(%swift.refcounted* %0) // CHECK: ret %swift.refcounted* %0 func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject { var (g,t) = Builtin.unsafeGuaranteed(x) Builtin.unsafeGuaranteedEnd(t) return g } // CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test // CHECK-NEXT: {{.*}}: // CHECK-NEXT: alloca // CHECK-NEXT: memset // CHECK-NEXT: store // CHECK-NEXT: ret void func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(x) } // CHECK-LABEL: define {{.*}} @{{.*}}atomicload func atomicload(_ p: Builtin.RawPointer) { // CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8 let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p) // CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} syncscope("singlethread") monotonic, align 4 let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p) // CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} syncscope("singlethread") acquire, align 8 let c: Builtin.Int64 = Builtin.atomicload_acquire_volatile_singlethread_Int64(p) // CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4 // CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p) // CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8 Builtin.atomicstore_unordered_RawPointer(p, a) // CHECK: store atomic i32 [[B]], i32* {{%.*}} syncscope("singlethread") monotonic, align 4 Builtin.atomicstore_monotonic_singlethread_Int32(p, b) // CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} syncscope("singlethread") release, align 8 Builtin.atomicstore_release_volatile_singlethread_Int64(p, c) // CHECK: [[D1:%.*]] = bitcast float [[D]] to i32 // CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4 Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d) } // CHECK-LABEL: define {{.*}} @"$s8builtins14stringObjectOryS2u_SutF"(i64 %0, i64 %1) // CHECK: %4 = or i64 %0, %1 // CHECK-NEXT: ret i64 %4 func stringObjectOr(_ x: UInt, _ y: UInt) -> UInt { return UInt(Builtin.stringObjectOr_Int64( x._value, y._value)) } func createInt(_ fn: () -> ()) throws {} // CHECK-LABEL: define {{.*}}testForceTry // CHECK: call swiftcc void @swift_unexpectedError(%swift.error* func testForceTry(_ fn: () -> ()) { try! createInt(fn) } // CHECK-LABEL: declare{{( dllimport)?}} swiftcc void @swift_unexpectedError(%swift.error* enum MyError : Error { case A, B } throw MyError.A /// Builtin.globalStringTablePointer must be reduced to a string_literal instruction before IRGen. IRGen /// should make this a trap. // CHECK-LABEL: define {{.*}}globalStringTablePointer // CHECK: call void @llvm.trap() // CHECK: ret i8* undef @_transparent func globalStringTablePointerUse(_ str: String) -> Builtin.RawPointer { return Builtin.globalStringTablePointer(str); } // CHECK-LABEL: define {{.*}}convertTaskToJob // CHECK: call %swift.refcounted* @swift_retain(%swift.refcounted* returned %0) // CHECK-NEXT: [[T0:%.*]] = bitcast %swift.refcounted* %0 to i8* // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8, i8* [[T0]], i64 16 // CHECK-NEXT: [[T2:%.*]] = bitcast i8* [[T1]] to %swift.job* // CHECK-NEXT: ret %swift.job* [[T2]] func convertTaskToJob(_ task: Builtin.NativeObject) -> Builtin.Job { return Builtin.convertTaskToJob(task) } // CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
apache-2.0
exyte/Macaw
Source/animation/layer_animation/FuncBounds.swift
1
2753
func solveEquation(a: Double, b: Double, c: Double) -> (s1: Double?, s2: Double?) { let epsilon: Double = 0.000000001 if abs(a) < epsilon { if abs(b) < epsilon { return (.none, .none) } let s = -c / b if 0.0 < s && s < 1.0 { return (s, .none) } return (.none, .none) } let b2ac = b * b - 4.0 * c * a if b2ac < 0.0 { return (.none, .none) } let sqrtb2ac = b2ac.squareRoot() let s1 = (-b + sqrtb2ac) / (2.0 * a) var r1: Double? = .none if (s1 >= 0.0) && (s1 <= 1.0) { r1 = s1 } let s2 = (-b - sqrtb2ac) / (2.0 * a) var r2: Double? = .none if (s2 >= 0.0) && (s2 <= 1.0) { r2 = s2 } return (r1, r2) } func boundsWithDerivative(p0: Point, p1: Point, p2: Point, p3: Point) -> Rect? { let ax = -3 * p0.x + 9 * p1.x - 9 * p2.x + 3 * p3.x let bx = 6 * p0.x - 12 * p1.x + 6 * p2.x let cx = 3 * p1.x - 3 * p0.x let sx = solveEquation(a: ax, b: bx, c: cx) let ay = -3 * p0.y + 9 * p1.y - 9 * p2.y + 3 * p3.y let by = 6 * p0.y - 12 * p1.y + 6 * p2.y let cy = 3 * p1.y - 3 * p0.y let sy = solveEquation(a: ay, b: by, c: cy) let solutions = [0, 1, sx.s1, sx.s2, sy.s1, sy.s2].compactMap { $0 } var minX: Double? = .none var minY: Double? = .none var maxX: Double? = .none var maxY: Double? = .none for s in solutions { let p = BezierFunc2D(s, p0: p0, p1: p1, p2: p2, p3: p3) if let mx = minX { if mx > p.x { minX = p.x } } else { minX = p.x } if let my = minY { if my > p.y { minY = p.y } } else { minY = p.y } if let mx = maxX { if mx < p.x { maxX = p.x } } else { maxX = p.x } if let my = maxY { if my < p.y { maxY = p.y } } else { maxY = p.y } } if let x = minX, let mx = maxX, let y = minY, let my = maxY { return Rect(x: x, y: y, w: mx - x, h: my - y) } return .none } func boundsForFunc(_ func2d: Func2D) -> Rect { var p = func2d(0.0) var minX = p.x var minY = p.y var maxX = minX var maxY = minY for t in stride(from: 0.0, to: 1.0, by: 0.01) { p = func2d(t) if minX > p.x { minX = p.x } if minY > p.y { minY = p.y } if maxX < p.x { maxX = p.x } if maxY < p.y { maxY = p.y } } return Rect(x: minX, y: minY, w: maxX - minX, h: maxY - minY) }
mit