repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
choofie/MusicTinder | MusicTinder/Classes/BusinessLogic/Services/URLProvider.swift | 1 | 3622 | //
// URLProvider.swift
// MusicTinder
//
// Created by Mate Lorincz on 05/11/16.
// Copyright © 2016 MateLorincz. All rights reserved.
//
import Foundation
enum ResultFormat : String {
case JSON = "&format=json"
case XML = ""
}
struct URLProvider {
fileprivate static let apiKey = "81c412de78ecc2616b61ec137f530ef8"
// base URLs
fileprivate static let lastFMBaseURL = "https://ws.audioscrobbler.com"
fileprivate static let iTunesBaseURL = "https://itunes.apple.com"
// Artist Service Endpoints
fileprivate static let artistSearchEndpoint = "/2.0/?method=artist.search&artist=ARTIST_NAME&api_key=YOUR_API_KEY"
fileprivate static let artistGetSimilarEndpoint = "/2.0/?method=artist.getsimilar&artist=ARTIST_NAME&api_key=YOUR_API_KEY"
fileprivate static let artistGetInfoEndpoint = "/2.0/?method=artist.getinfo&artist=ARTIST_NAME&api_key=YOUR_API_KEY"
// Chart Service Endpoints
fileprivate static let chartGetTopArtistsEndpoint = "/2.0/?method=chart.gettopartists&api_key=YOUR_API_KEY"
// iTunes Service Endpoints
fileprivate static let iTunesArtistSearchEndpoint = "/search?term=ARTIST_NAME&entity=song"
static func artistSearchURLString(_ artistName: String?) -> String? {
var urlString = lastFMBaseURL + artistSearchEndpoint
let validatedArtistName = artistName?.replacingOccurrences(of: " ", with: "+")
urlString = urlString.replacingOccurrences(of: "ARTIST_NAME", with: validatedArtistName ?? "")
urlString = urlString.replacingOccurrences(of: "YOUR_API_KEY", with: apiKey)
print("[DOWNLOAD] - artist search from URL: \(urlString)")
return urlString
}
static func similartArtistsURLString(_ artistName: String?) -> String? {
var urlString = lastFMBaseURL + artistGetSimilarEndpoint
let validatedArtistName = artistName?.replacingOccurrences(of: " ", with: "+")
urlString = urlString.replacingOccurrences(of: "ARTIST_NAME", with: validatedArtistName ?? "")
urlString = urlString.replacingOccurrences(of: "YOUR_API_KEY", with: apiKey)
print("[DOWNLOAD] - similar artists from URL: \(urlString)")
return urlString
}
static func artistInfoURLString(_ artistName: String?) -> String? {
var urlString = lastFMBaseURL + artistGetInfoEndpoint
let validatedArtistName = artistName?.replacingOccurrences(of: " ", with: "+")
urlString = urlString.replacingOccurrences(of: "ARTIST_NAME", with: validatedArtistName ?? "")
urlString = urlString.replacingOccurrences(of: "YOUR_API_KEY", with: apiKey)
print("[DOWNLOAD] - artist info from URL: \(urlString)")
return urlString
}
static func iTunesAtistURLString(_ artistName: String?) -> String? {
var urlString = iTunesBaseURL + iTunesArtistSearchEndpoint
let validatedArtistName = artistName?.replacingOccurrences(of: " ", with: "+")
urlString = urlString.replacingOccurrences(of: "ARTIST_NAME", with: validatedArtistName ?? "")
print("[DOWNLOAD] - iTunes artist from URL: \(urlString)")
return urlString
}
static func topArtistsURL() -> String? {
var urlString = lastFMBaseURL + chartGetTopArtistsEndpoint
urlString = urlString.replacingOccurrences(of: "YOUR_API_KEY", with: apiKey)
print("[DOWNLOAD] - top artists from URL: \(urlString)")
return urlString
}
}
extension String {
func appendResultFormat(_ format: ResultFormat) -> String {
return self + format.rawValue
}
}
| mit | a862a1d44d15a5cab657cfbac18f9e5b | 40.62069 | 126 | 0.683789 | 4.548995 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Private/ImageDownloader.swift | 1 | 1919 | import Foundation
class ImageDownloader {
private let eventBus: EventBus
private let api: API
private let imageRepository: ImageRepository
init(eventBus: EventBus, api: API, imageRepository: ImageRepository) {
self.eventBus = eventBus
self.api = api
self.imageRepository = imageRepository
}
struct DownloadRequest: Equatable {
var imageIdentifier: String
var imageContentHashSha1: String
init(characteristics: ImageCharacteristics) {
imageIdentifier = characteristics.identifier
imageContentHashSha1 = characteristics.contentHashSha1.base64EncodedString
}
}
func downloadImages(
requests: [DownloadRequest],
parentProgress: Progress,
completionHandler: @escaping () -> Void
) {
guard !requests.isEmpty else {
completionHandler()
return
}
var pendingImageIdentifiers = requests
for request in requests {
let identifier = request.imageIdentifier
let sha1 = request.imageContentHashSha1
api.fetchImage(identifier: identifier, contentHashSha1: sha1) { (data) in
guard let idx = pendingImageIdentifiers.firstIndex(of: request) else { return }
pendingImageIdentifiers.remove(at: idx)
var completedUnitCount = parentProgress.completedUnitCount
completedUnitCount += 1
parentProgress.completedUnitCount = completedUnitCount
if let data = data {
let event = ImageDownloadedEvent(identifier: request.imageIdentifier, pngImageData: data)
self.eventBus.post(event)
}
if pendingImageIdentifiers.isEmpty {
completionHandler()
}
}
}
}
}
| mit | 747c5f19d7daeb0b31880a7216c68462 | 30.459016 | 109 | 0.608129 | 6.015674 | false | false | false | false |
Witcast/witcast-ios | WiTcast/Model/ItemLocal.swift | 1 | 528 | //
// ItemLocal.swift
// WiTcast
//
// Created by Tanakorn Phoochaliaw on 8/6/2560 BE.
// Copyright © 2560 Tanakorn Phoochaliaw. All rights reserved.
//
import UIKit
import RealmSwift
class ItemLocal: Object {
dynamic var episodeId = 0;
dynamic var downloadStatus = "None";
dynamic var isFavourite = false;
dynamic var downloadPath = "";
dynamic var downloadPercent = 0;
dynamic var lastDulation = 0.0;
override class func primaryKey() -> String {
return "episodeId"
}
}
| apache-2.0 | 9c6414dfc19061b4db496874ec6f723f | 20.958333 | 63 | 0.662239 | 3.685315 | false | false | false | false |
austinzheng/swift | test/decl/protocol/req/missing_conformance.swift | 11 | 4876 | // RUN: %target-typecheck-verify-swift
// Test candidates for witnesses that are missing conformances
// in various ways.
protocol LikeSetAlgebra {
func onion(_ other: Self) -> Self // expected-note {{protocol requires function 'onion' with type '(X) -> X'; do you want to add a stub?}}
func indifference(_ other: Self) -> Self // expected-note {{protocol requires function 'indifference' with type '(X) -> X'; do you want to add a stub?}}
}
protocol LikeOptionSet : LikeSetAlgebra, RawRepresentable {}
extension LikeOptionSet where RawValue : FixedWidthInteger {
func onion(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}}
func indifference(_ other: Self) -> Self { return self } // expected-note {{candidate would match if 'X.RawValue' conformed to 'FixedWidthInteger'}}
}
struct X : LikeOptionSet {}
// expected-error@-1 {{type 'X' does not conform to protocol 'LikeSetAlgebra'}}
// expected-error@-2 {{type 'X' does not conform to protocol 'RawRepresentable'}}
protocol IterProtocol {}
protocol LikeSequence {
associatedtype Iter : IterProtocol // expected-note {{unable to infer associated type 'Iter' for protocol 'LikeSequence'}}
func makeIter() -> Iter
}
extension LikeSequence where Self == Self.Iter {
func makeIter() -> Self { return self } // expected-note {{candidate would match and infer 'Iter' = 'Y' if 'Y' conformed to 'IterProtocol'}}
}
struct Y : LikeSequence {} // expected-error {{type 'Y' does not conform to protocol 'LikeSequence'}}
protocol P1 {
associatedtype Result
func get() -> Result // expected-note {{protocol requires function 'get()' with type '() -> Result'; do you want to add a stub?}}
func got() // expected-note {{protocol requires function 'got()' with type '() -> ()'; do you want to add a stub?}}
}
protocol P2 {
static var singularThing: Self { get }
}
extension P1 where Result : P2 {
func get() -> Result { return Result.singularThing } // expected-note {{candidate would match if 'Result' conformed to 'P2'}}
}
protocol P3 {}
extension P1 where Self : P3 {
func got() {} // expected-note {{candidate would match if 'Z<T1, T2, T3, Result, T4>' conformed to 'P3'}}
}
struct Z<T1, T2, T3, Result, T4> : P1 {} // expected-error {{type 'Z<T1, T2, T3, Result, T4>' does not conform to protocol 'P1'}}
protocol P4 {
func this() // expected-note 2 {{protocol requires function 'this()' with type '() -> ()'; do you want to add a stub?}}
}
protocol P5 {}
extension P4 where Self : P5 {
func this() {} // expected-note {{candidate would match if 'W' conformed to 'P5'}}
//// expected-note@-1 {{candidate would match if 'S<T>.SS' conformed to 'P5'}}
}
struct W : P4 {} // expected-error {{type 'W' does not conform to protocol 'P4'}}
struct S<T> {
struct SS : P4 {} // expected-error {{type 'S<T>.SS' does not conform to protocol 'P4'}}
}
class C {}
protocol P6 {
associatedtype T : C // expected-note {{unable to infer associated type 'T' for protocol 'P6'}}
func f(t: T)
}
struct A : P6 { // expected-error {{type 'A' does not conform to protocol 'P6'}}
func f(t: Int) {} // expected-note {{candidate can not infer 'T' = 'Int' because 'Int' is not a class type and so can't inherit from 'C'}}
}
protocol P7 {}
protocol P8 {
associatedtype T : P7 // expected-note {{unable to infer associated type 'T' for protocol 'P8'}}
func g(t: T)
}
struct B : P8 { // expected-error {{type 'B' does not conform to protocol 'P8'}}
func g(t: (Int, String)) {} // expected-note {{candidate can not infer 'T' = '(Int, String)' because '(Int, String)' is not a nominal type and so can't conform to 'P7'}}
}
protocol P9 {
func foo() // expected-note {{protocol requires function 'foo()' with type '() -> ()'; do you want to add a stub?}}
}
class C2 {}
extension P9 where Self : C2 {
func foo() {} // expected-note {{candidate would match if 'C3' subclassed 'C2'}}
}
class C3 : P9 {} // expected-error {{type 'C3' does not conform to protocol 'P9'}}
protocol P10 {
associatedtype A
func bar() // expected-note {{protocol requires function 'bar()' with type '() -> ()'; do you want to add a stub?}}
}
extension P10 where A == Int {
func bar() {} // expected-note {{candidate would match if 'A' was the same type as 'Int'}}
}
struct S2<A> : P10 {} // expected-error {{type 'S2<A>' does not conform to protocol 'P10'}}
protocol P11 {}
protocol P12 {
associatedtype A : P11 // expected-note {{unable to infer associated type 'A' for protocol 'P12'}}
func bar() -> A
}
extension Int : P11 {}
struct S3 : P12 { // expected-error {{type 'S3' does not conform to protocol 'P12'}}
func bar() -> P11 { return 0 }
// expected-note@-1 {{candidate can not infer 'A' = 'P11' because 'P11' is not a nominal type and so can't conform to 'P11'}}
}
| apache-2.0 | a9a007c7e3c8f0e40f83dd7c9aadf690 | 42.535714 | 173 | 0.659967 | 3.585294 | false | false | false | false |
colourful987/Topic_Demo | Advanced & Practical Enum usage in Swift/Advanced & Practical Enum usage in Swift(下集).playground/Contents.swift | 1 | 8229 | //: Advanced & Practical Enum usage in Swift下集
import UIKit
/*
swift中的CustomStringConvertible协议需要我们为类添加一个说明
即一个description:String类型的可读变量
声明如下:
protocol CustomStringConvertible {
var description: String { get }
}
*/
// 继续上文中的Trade例子
// 让Trade类遵循该协议 为此我们需要添加description计算变量
// 它是通过枚举值来生成一个说明
enum Trade: CustomStringConvertible {
case Buy, Sell
var description: String {
switch self {
case Buy: return "We're buying something"
case Sell: return "We're selling something"
}
}
}
let action = Trade.Buy
print("this action is \(action)")
//: 我们以一个账号管理系统加深枚举遵循协议使用
// 首先定义一个协议
// 条件有三:剩余资金(可读变量)、资金转入和资金移除两个方法
protocol AccountCompatible {
var remainingFunds: Int { get }
mutating func addFunds(amount: Int) throws
mutating func removeFunds(amount: Int) throws
}
// 声明一个Account类
enum Account {
case Empty
case Funds(remaining: Int)
enum Error: ErrorType {
case Overdraft(amount: Int)
}
var remainingFunds: Int {
switch self {
case Empty: return 0
case Funds(let remaining): return remaining
}
}
}
// 我们不想把遵循协议的内容也放到Account主题中实现,为此采用extension来实现。
extension Account: AccountCompatible {
mutating func addFunds(amount: Int) throws {
var newAmount = amount
if case let .Funds(remaining) = self {
newAmount += remaining
}
if newAmount < 0 {
throw Error.Overdraft(amount: -newAmount)
} else if newAmount == 0 {
self = .Empty
} else {
self = .Funds(remaining: newAmount)
}
}
mutating func removeFunds(amount: Int) throws {
try self.addFunds(amount * -1)
}
}
var account = Account.Funds(remaining: 20)
print("add: ", try? account.addFunds(10))
print ("remove 1: ", try? account.removeFunds(15))
print ("remove 2: ", try? account.removeFunds(55))
//: 枚举中使用extension分离用例声明和方法声明
// Entities枚举声明
enum Entities {
case Soldier(x: Int, y: Int)
case Tank(x: Int, y: Int)
case Player(x: Int, y: Int)
}
// Entities枚举方法声明 其实是对Entities的扩展
extension Entities {
mutating func move(dist: CGVector) {}
mutating func attack() {}
}
// Entities遵循CustomStringConvertible协议
extension Entities: CustomStringConvertible {
var description: String {
switch self {
case let .Soldier(x, y): return "\(x), \(y)"
case let .Tank(x, y): return "\(x), \(y)"
case let .Player(x, y): return "\(x), \(y)"
}
}
}
//: 枚举中的泛型
// 简单例子
enum Either<T1, T2> {
case Left(T1)
case Right(T2)
}
// 为泛型加上条件约束
enum Bag<T: SequenceType where T.Generator.Element==Equatable> {
case Empty
case Full(contents: T)
}
//: 枚举中的递归
// 注意case前面的关键字indirect,倘若多个case前都可以递归 那么简化写法可以是把indirect写在enum前面即可
enum FileNode {
case File(name: String)
indirect case Folder(name: String, files: [FileNode])
}
// 如下
indirect enum Tree<Element: Comparable> {
case Empty
case Node(Tree<Element>,Element,Tree<Element>)
}
//: Comparing Enums with associated values
enum Trade_3 {
case Buy(stock: String, amount: Int)
case Sell(stock: String, amount: Int)
}
var trade1 = Trade_3.Buy(stock:"stock1",amount:2)
var trade2 = Trade_3.Buy(stock: "stock2", amount: 3)
// 倘若我们使用if trade1 == trade2{} 进行比较 那么报错为你未实现Trade_3的类型之间的比较
// 为此我们需要实现Trade_3类型的 ==
func ==(lhs: Trade_3, rhs: Trade_3) -> Bool {
switch (lhs, rhs) {
case let (.Buy(stock1, amount1), .Buy(stock2, amount2))
where stock1 == stock2 && amount1 == amount2:
return true
case let (.Sell(stock1, amount1), .Sell(stock2, amount2))
where stock1 == stock2 && amount1 == amount2:
return true
default: return false
}
}
//: 自定义构造方法
enum Device {
case AppleWatch
static func fromSlang(term: String) -> Device? {
if term == "iWatch" {
return .AppleWatch
}
return nil
}
}
// 上面使用了static 方法实现 现在使用init?构造方法实现
enum Device_1 {
case AppleWatch
init?(term: String) {
if term == "iWatch" {
self = .AppleWatch
}
return nil
}
}
// 当然我们还能这么干
enum NumberCategory {
case Small
case Medium
case Big
case Huge
init(number n: Int) {
if n < 10000 { self = .Small }
else if n < 1000000 { self = .Medium }
else if n < 100000000 { self = .Big }
else { self = .Huge }
}
}
let aNumber = NumberCategory(number: 100)
print(aNumber)
//: ErrorType的使用
// ErrorType是一个空协议 这样我们就能自定义错误了!!
enum DecodeError: ErrorType {
case TypeMismatch(expected: String, actual: String)
case MissingKey(String)
case Custom(String)
}
// 不如来看下HTTP/REST API中错误处理
enum APIError : ErrorType {
// Can't connect to the server (maybe offline?)
case ConnectionError(error: NSError)
// The server responded with a non 200 status code
case ServerError(statusCode: Int, error: NSError)
// We got no data (0 bytes) back from the server
case NoDataError
// The server response can't be converted from JSON to a Dictionary
case JSONSerializationError(error: ErrorType)
// The Argo decoding Failed
case JSONMappingError(converstionError: DecodeError)
}
// 状态码使用
enum HttpError: String {
case Code400 = "Bad Request"
case Code401 = "Unauthorized"
case Code402 = "Payment Required"
case Code403 = "Forbidden"
case Code404 = "Not Found"
}
// JSON数据转换
/* 这是作者从JSON第三方库中提取的代码
enum JSON {
case JSONString(Swift.String)
case JSONNumber(Double)
case JSONObject([String : JSONValue])
case JSONArray([JSONValue])
case JSONBool(Bool)
case JSONNull
}
*/
// 联系实际 我们经常会设定identifier值
enum CellType: String {
case ButtonValueCell = "ButtonValueCell"
case UnitEditCell = "UnitEditCell"
case LabelCell = "LabelCell"
case ResultLabelCell = "ResultLabelCell"
}
// 单位转换
enum Liquid: Float {
case ml = 1.0
case l = 1000.0
func convert(amount amount: Float, to: Liquid) -> Float {
if self.rawValue < to.rawValue {
return (self.rawValue / to.rawValue) * amount
} else {
return (self.rawValue * to.rawValue) * amount
}
}
}
// Convert liters to milliliters
print (Liquid.l.convert(amount: 5, to: Liquid.ml))
// 游戏案例
enum FlyingBeast { case Dragon, Hippogriff, Gargoyle }
enum Horde { case Ork, Troll }
enum Player { case Mage, Warrior, Barbarian }
enum NPC { case Vendor, Blacksmith }
enum Element { case Tree, Fence, Stone }
protocol Hurtable {}
protocol Killable {}
protocol Flying {}
protocol Attacking {}
protocol Obstacle {}
extension FlyingBeast: Hurtable, Killable, Flying, Attacking {}
extension Horde: Hurtable, Killable, Attacking {}
extension Player: Hurtable, Obstacle {}
extension NPC: Hurtable {}
extension Element: Obstacle {}
// 以字符形式输入代码,例如实际开发中视图的背景图片
enum DetailViewImages: String {
case Background = "bg1.png"
case Sidebar = "sbg.png"
case ActionButton1 = "btn1_1.png"
case ActionButton2 = "btn2_1.png"
}
// API Endpoints
enum Instagram {
enum Media {
case Popular
case Shortcode(id: String)
case Search(lat: Float, min_timestamp: Int, lng: Float, max_timestamp: Int, distance: Int)
}
enum Users {
case User(id: String)
case Feed
case Recent(id: String)
}
}
| mit | 4264740b85fbd7dbed340fb0aecef416 | 22.281646 | 98 | 0.64578 | 3.545542 | false | false | false | false |
tardieu/swift | test/expr/cast/array_downcast_Foundation.swift | 13 | 3486 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// FIXME: BEGIN -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %clang-importer-sdk-path/swift-modules/Foundation.swift
// FIXME: END -enable-source-import hackaround
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -typecheck %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) %s -dump-ast -verify 2>&1 | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
func testDowncastObjectToArray(obj: AnyObject, objImplicit: AnyObject!) {
var nsstrArr1 = (obj as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}}{{39-40=}}
var strArr1 = (obj as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}}{{35-36=}}
var nsstrArr2 = (objImplicit as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}}{{47-48=}}
var strArr2 = (objImplicit as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}}{{43-44=}}
}
func testArrayDowncast(arr: [AnyObject], arrImplicit: [AnyObject]!) {
var nsstrArr1 = (arr as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}} {{39-40=}}
var strArr1 = (arr as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}} {{35-36=}}
var nsstrArr2 = (arrImplicit as! [NSString])! // expected-error{{cannot force unwrap value of non-optional type '[NSString]'}} {{47-48=}}
var strArr2 = (arrImplicit as! [String])! // expected-error{{cannot force unwrap value of non-optional type '[String]'}} {{43-44=}}
}
func testDowncastNSArrayToArray(nsarray: NSArray) {
_ = nsarray as! [NSString]
_ = nsarray as! [String]
}
// CHECK-LABEL: testDowncastOptionalObject
func testDowncastOptionalObject(obj: AnyObject?!) -> [String]? {
// CHECK: (optional_evaluation_expr implicit type='[String]?'
// CHECK-NEXT: (inject_into_optional implicit type='[String]?'
// CHECK: (forced_checked_cast_expr type='[String]'{{.*value_cast}}
// CHECK: (bind_optional_expr implicit type='AnyObject'
// CHECK-NEXT: (force_value_expr implicit type='AnyObject?'
// CHECK-NEXT: (declref_expr type='AnyObject?!'
return obj as! [String]?
}
// CHECK-LABEL: testDowncastOptionalObjectConditional
func testDowncastOptionalObjectConditional(obj: AnyObject?!) -> [String]?? {
// CHECK: (optional_evaluation_expr implicit type='[String]??'
// CHECK-NEXT: (inject_into_optional implicit type='[String]??'
// CHECK-NEXT: (optional_evaluation_expr implicit type='[String]?'
// CHECK-NEXT: (inject_into_optional implicit type='[String]?'
// CHECK-NEXT: (bind_optional_expr implicit type='[String]'
// CHECK-NEXT: (conditional_checked_cast_expr type='[String]?' {{.*value_cast}} writtenType='[String]?'
// CHECK-NEXT: (bind_optional_expr implicit type='AnyObject'
// CHECK-NEXT: (bind_optional_expr implicit type='AnyObject?'
// CHECK-NEXT: (declref_expr type='AnyObject?!'
return obj as? [String]?
}
// Do not crash examining the casted-to (or tested) type if it is
// invalid (null or error_type).
class rdar28583595 : NSObject {
public func test(i: Int) {
if i is Array {} // expected-error {{generic parameter 'Element' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
}
}
| apache-2.0 | 777f15eac64d5943002c6b3f3ef5f32d | 50.264706 | 139 | 0.698221 | 3.692797 | false | true | false | false |
catloafsoft/AudioKit | Examples/iOS/AnalogSynthX/AnalogSynthX/SMSegmentView/SMBasicSegmentView.swift | 1 | 6121 | //
// SMBasicSegmentView.swift
// SMSegmentViewController
//
// Created by mlaskowski on 01/10/15.
// Copyright © 2016 si.ma. All rights reserved.
//
import Foundation
import UIKit
public enum SegmentOrganiseMode: Int {
case SegmentOrganiseHorizontal = 0
case SegmentOrganiseVertical
}
public protocol SMSegmentViewDelegate: class {
func segmentView(segmentView: SMBasicSegmentView, didSelectSegmentAtIndex index: Int)
}
public class SMBasicSegmentView: UIView {
public var segments: [SMBasicSegment] = [] {
didSet {
var i=0;
for segment in segments {
segment.index = i
i++
segment.segmentView = self
self.addSubview(segment)
}
self.updateFrameForSegments()
}
}
public weak var delegate: SMSegmentViewDelegate?
public private(set) var indexOfSelectedSegment: Int = NSNotFound
var numberOfSegments: Int {get {
return segments.count
}}
@IBInspectable public var vertical: Bool = false{
didSet {
let mode = vertical ? SegmentOrganiseMode.SegmentOrganiseVertical : SegmentOrganiseMode.SegmentOrganiseHorizontal
self.orientationChangedTo(mode)
}
}
// Segment Separator
@IBInspectable public var separatorColour: UIColor = UIColor.lightGrayColor() {
didSet {
self.setNeedsDisplay()
}
}
@IBInspectable public var separatorWidth: CGFloat = 1.0 {
didSet {
self.updateFrameForSegments()
}
}
public override func layoutSubviews() {
super.layoutSubviews()
self.updateFrameForSegments()
}
public func orientationChangedTo(mode: SegmentOrganiseMode){
for segment in self.segments {
segment.orientationChangedTo(mode)
}
setNeedsDisplay()
}
public func updateFrameForSegments() {
if self.segments.count == 0 {
return
}
let count = self.segments.count
if count > 1 {
if self.vertical == false {
let segmentWidth = (self.frame.size.width - self.separatorWidth*CGFloat(count-1)) / CGFloat(count)
var originX: CGFloat = 0.0
for segment in self.segments {
segment.frame = CGRect(x: originX, y: 0.0, width: segmentWidth, height: self.frame.size.height)
originX += segmentWidth + self.separatorWidth
}
}
else {
let segmentHeight = (self.frame.size.height - self.separatorWidth*CGFloat(count-1)) / CGFloat(count)
var originY: CGFloat = 0.0
for segment in self.segments {
segment.frame = CGRect(x: 0.0, y: originY, width: self.frame.size.width, height: segmentHeight)
originY += segmentHeight + self.separatorWidth
}
}
}
else {
self.segments[0].frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
}
self.setNeedsDisplay()
}
public func drawSeparatorWithContext(context: CGContextRef) {
CGContextSaveGState(context)
if self.segments.count > 1 {
let path = CGPathCreateMutable()
if self.vertical == false {
var originX: CGFloat = self.segments[0].frame.size.width + self.separatorWidth/2.0
for index in 1..<self.segments.count {
CGPathMoveToPoint(path, nil, originX, 0.0)
CGPathAddLineToPoint(path, nil, originX, self.frame.size.height)
originX += self.segments[index].frame.width + self.separatorWidth
}
}
else {
var originY: CGFloat = self.segments[0].frame.size.height + self.separatorWidth/2.0
for index in 1..<self.segments.count {
CGPathMoveToPoint(path, nil, 0.0, originY)
CGPathAddLineToPoint(path, nil, self.frame.size.width, originY)
originY += self.segments[index].frame.height + self.separatorWidth
}
}
CGContextAddPath(context, path)
CGContextSetStrokeColorWithColor(context, self.separatorColour.CGColor)
CGContextSetLineWidth(context, self.separatorWidth)
CGContextDrawPath(context, CGPathDrawingMode.Stroke)
}
CGContextRestoreGState(context)
}
// MARK: Drawing Segment Separators
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
let context = UIGraphicsGetCurrentContext()!
self.drawSeparatorWithContext(context)
}
// MARK: Actions
public func selectSegmentAtIndex(index: Int) {
assert(index >= 0 && index < self.segments.count, "Index at \(index) is out of bounds")
if self.indexOfSelectedSegment != NSNotFound {
let previousSelectedSegment = self.segments[self.indexOfSelectedSegment]
previousSelectedSegment.setSelected(false, inView: self)
}
self.indexOfSelectedSegment = index
let segment = self.segments[index]
segment.setSelected(true, inView: self)
self.delegate?.segmentView(self, didSelectSegmentAtIndex: index)
}
public func deselectSegment() {
if self.indexOfSelectedSegment != NSNotFound {
let segment = self.segments[self.indexOfSelectedSegment]
segment.setSelected(false, inView: self)
self.indexOfSelectedSegment = NSNotFound
}
}
public func addSegment(segment: SMBasicSegment){
segment.index = self.segments.count
self.segments.append(segment)
segment.segmentView = self
self.updateFrameForSegments()
self.addSubview(segment)
}
} | mit | 79daeca5eb66622fe37c40df3a979843 | 33.195531 | 125 | 0.590033 | 5.177665 | false | false | false | false |
kstaring/swift | test/stdlib/TestAffineTransform.swift | 1 | 19320 | // 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: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
import Foundation
#if os(OSX)
#if FOUNDATION_XCTEST
import XCTest
class TestAffineTransformSuper : XCTestCase { }
#else
import StdlibUnittest
class TestAffineTransformSuper { }
#endif
func expectEqualWithAccuracy(_ lhs: Double, _ rhs: Double, accuracy: Double, _ message: String = "", file: String = #file, line: UInt = #line) {
expectTrue(fabs(lhs - rhs) < accuracy, message, file: file, line: line)
}
extension AffineTransform {
func transform(_ aRect: NSRect) -> NSRect {
return NSRect(origin: transform(aRect.origin), size: transform(aRect.size))
}
}
class TestAffineTransform : TestAffineTransformSuper {
private let accuracyThreshold = 0.001
func checkPointTransformation(_ transform: AffineTransform, point: NSPoint, expectedPoint: NSPoint, _ message: String = "", file: String = #file, line: UInt = #line) {
let newPoint = transform.transform(point)
expectEqualWithAccuracy(Double(newPoint.x), Double(expectedPoint.x), accuracy: accuracyThreshold,
"x (expected: \(expectedPoint.x), was: \(newPoint.x)): \(message)", file: file, line: line)
expectEqualWithAccuracy(Double(newPoint.y), Double(expectedPoint.y), accuracy: accuracyThreshold,
"y (expected: \(expectedPoint.y), was: \(newPoint.y)): \(message)", file: file, line: line)
}
func checkSizeTransformation(_ transform: AffineTransform, size: NSSize, expectedSize: NSSize, _ message: String = "", file: String = #file, line: UInt = #line) {
let newSize = transform.transform(size)
expectEqualWithAccuracy(Double(newSize.width), Double(expectedSize.width), accuracy: accuracyThreshold,
"width (expected: \(expectedSize.width), was: \(newSize.width)): \(message)", file: file, line: line)
expectEqualWithAccuracy(Double(newSize.height), Double(expectedSize.height), accuracy: accuracyThreshold,
"height (expected: \(expectedSize.height), was: \(newSize.height)): \(message)", file: file, line: line)
}
func checkRectTransformation(_ transform: AffineTransform, rect: NSRect, expectedRect: NSRect, _ message: String = "", file: String = #file, line: UInt = #line) {
let newRect = transform.transform(rect)
checkPointTransformation(transform, point: newRect.origin, expectedPoint: expectedRect.origin,
"origin (expected: \(expectedRect.origin), was: \(newRect.origin)): \(message)", file: file, line: line)
checkSizeTransformation(transform, size: newRect.size, expectedSize: expectedRect.size,
"size (expected: \(expectedRect.size), was: \(newRect.size)): \(message)", file: file, line: line)
}
func test_BasicConstruction() {
let defaultAffineTransform = AffineTransform()
let identityTransform = AffineTransform.identity
expectEqual(defaultAffineTransform, identityTransform)
// The diagonal entries (1,1) and (2,2) of the identity matrix are ones. The other entries are zeros.
// TODO: These should use DBL_MAX but it's not available as part of Glibc on Linux
expectEqualWithAccuracy(Double(identityTransform.m11), Double(1), accuracy: accuracyThreshold)
expectEqualWithAccuracy(Double(identityTransform.m22), Double(1), accuracy: accuracyThreshold)
expectEqualWithAccuracy(Double(identityTransform.m12), Double(0), accuracy: accuracyThreshold)
expectEqualWithAccuracy(Double(identityTransform.m21), Double(0), accuracy: accuracyThreshold)
expectEqualWithAccuracy(Double(identityTransform.tX), Double(0), accuracy: accuracyThreshold)
expectEqualWithAccuracy(Double(identityTransform.tY), Double(0), accuracy: accuracyThreshold)
}
func test_IdentityTransformation() {
let identityTransform = AffineTransform.identity
func checkIdentityPointTransformation(_ point: NSPoint) {
checkPointTransformation(identityTransform, point: point, expectedPoint: point)
}
checkIdentityPointTransformation(NSPoint())
checkIdentityPointTransformation(NSPoint(x: CGFloat(24.5), y: CGFloat(10.0)))
checkIdentityPointTransformation(NSPoint(x: CGFloat(-7.5), y: CGFloat(2.0)))
func checkIdentitySizeTransformation(_ size: NSSize) {
checkSizeTransformation(identityTransform, size: size, expectedSize: size)
}
checkIdentitySizeTransformation(NSSize())
checkIdentitySizeTransformation(NSSize(width: CGFloat(13.0), height: CGFloat(12.5)))
checkIdentitySizeTransformation(NSSize(width: CGFloat(100.0), height: CGFloat(-100.0)))
}
func test_Translation() {
let point = NSPoint(x: CGFloat(0.0), y: CGFloat(0.0))
var noop = AffineTransform.identity
noop.translate(x: CGFloat(), y: CGFloat())
checkPointTransformation(noop, point: point, expectedPoint: point)
var translateH = AffineTransform.identity
translateH.translate(x: CGFloat(10.0), y: CGFloat())
checkPointTransformation(translateH, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat()))
var translateV = AffineTransform.identity
translateV.translate(x: CGFloat(), y: CGFloat(20.0))
checkPointTransformation(translateV, point: point, expectedPoint: NSPoint(x: CGFloat(), y: CGFloat(20.0)))
var translate = AffineTransform.identity
translate.translate(x: CGFloat(-30.0), y: CGFloat(40.0))
checkPointTransformation(translate, point: point, expectedPoint: NSPoint(x: CGFloat(-30.0), y: CGFloat(40.0)))
}
func test_Scale() {
let size = NSSize(width: CGFloat(10.0), height: CGFloat(10.0))
var noop = AffineTransform.identity
noop.scale(CGFloat(1.0))
checkSizeTransformation(noop, size: size, expectedSize: size)
var shrink = AffineTransform.identity
shrink.scale(CGFloat(0.5))
checkSizeTransformation(shrink, size: size, expectedSize: NSSize(width: CGFloat(5.0), height: CGFloat(5.0)))
var grow = AffineTransform.identity
grow.scale(CGFloat(3.0))
checkSizeTransformation(grow, size: size, expectedSize: NSSize(width: CGFloat(30.0), height: CGFloat(30.0)))
var stretch = AffineTransform.identity
stretch.scale(x: CGFloat(2.0), y: CGFloat(0.5))
checkSizeTransformation(stretch, size: size, expectedSize: NSSize(width: CGFloat(20.0), height: CGFloat(5.0)))
}
func test_Rotation_Degrees() {
let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
var noop = AffineTransform.identity
noop.rotate(byDegrees: CGFloat())
checkPointTransformation(noop, point: point, expectedPoint: point)
var tenEighty = AffineTransform.identity
tenEighty.rotate(byDegrees: CGFloat(1080.0))
checkPointTransformation(tenEighty, point: point, expectedPoint: point)
var rotateCounterClockwise = AffineTransform.identity
rotateCounterClockwise.rotate(byDegrees: CGFloat(90.0))
checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0)))
var rotateClockwise = AffineTransform.identity
rotateClockwise.rotate(byDegrees: CGFloat(-90.0))
checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0)))
var reflectAboutOrigin = AffineTransform.identity
reflectAboutOrigin.rotate(byDegrees: CGFloat(180.0))
checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0)))
}
func test_Rotation_Radians() {
let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
var noop = AffineTransform.identity
noop.rotate(byRadians: CGFloat())
checkPointTransformation(noop, point: point, expectedPoint: point)
var tenEighty = AffineTransform.identity
tenEighty.rotate(byRadians: CGFloat(6 * M_PI))
checkPointTransformation(tenEighty, point: point, expectedPoint: point)
var rotateCounterClockwise = AffineTransform.identity
rotateCounterClockwise.rotate(byRadians: CGFloat(M_PI_2))
checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0)))
var rotateClockwise = AffineTransform.identity
rotateClockwise.rotate(byRadians: CGFloat(-M_PI_2))
checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0)))
var reflectAboutOrigin = AffineTransform.identity
reflectAboutOrigin.rotate(byRadians: CGFloat(M_PI))
checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0)))
}
func test_Inversion() {
let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
var translate = AffineTransform.identity
translate.translate(x: CGFloat(-30.0), y: CGFloat(40.0))
var rotate = AffineTransform.identity
translate.rotate(byDegrees: CGFloat(30.0))
var scale = AffineTransform.identity
scale.scale(CGFloat(2.0))
var identityTransform = AffineTransform.identity
// append transformations
identityTransform.append(translate)
identityTransform.append(rotate)
identityTransform.append(scale)
// invert transformations
scale.invert()
rotate.invert()
translate.invert()
// append inverse transformations in reverse order
identityTransform.append(scale)
identityTransform.append(rotate)
identityTransform.append(translate)
checkPointTransformation(identityTransform, point: point, expectedPoint: point)
}
func test_TranslationComposed() {
var xyPlus5 = AffineTransform.identity
xyPlus5.translate(x: CGFloat(2.0), y: CGFloat(3.0))
xyPlus5.translate(x: CGFloat(3.0), y: CGFloat(2.0))
checkPointTransformation(xyPlus5, point: NSPoint(x: CGFloat(-2.0), y: CGFloat(-3.0)),
expectedPoint: NSPoint(x: CGFloat(3.0), y: CGFloat(2.0)))
}
func test_Scaling() {
var xyTimes5 = AffineTransform.identity
xyTimes5.scale(CGFloat(5.0))
checkPointTransformation(xyTimes5, point: NSPoint(x: CGFloat(-2.0), y: CGFloat(3.0)),
expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(15.0)))
var xTimes2YTimes3 = AffineTransform.identity
xTimes2YTimes3.scale(x: CGFloat(2.0), y: CGFloat(-3.0))
checkPointTransformation(xTimes2YTimes3, point: NSPoint(x: CGFloat(-1.0), y: CGFloat(3.5)),
expectedPoint: NSPoint(x: CGFloat(-2.0), y: CGFloat(-10.5)))
}
func test_TranslationScaling() {
var xPlus2XYTimes5 = AffineTransform.identity
xPlus2XYTimes5.translate(x: CGFloat(2.0), y: CGFloat())
xPlus2XYTimes5.scale(x: CGFloat(5.0), y: CGFloat(-5.0))
checkPointTransformation(xPlus2XYTimes5, point: NSPoint(x: CGFloat(1.0), y: CGFloat(2.0)),
expectedPoint: NSPoint(x: CGFloat(7.0), y: CGFloat(-10.0)))
}
func test_ScalingTranslation() {
var xyTimes5XPlus3 = AffineTransform.identity
xyTimes5XPlus3.scale(CGFloat(5.0))
xyTimes5XPlus3.translate(x: CGFloat(3.0), y: CGFloat())
checkPointTransformation(xyTimes5XPlus3, point: NSPoint(x: CGFloat(1.0), y: CGFloat(2.0)),
expectedPoint: NSPoint(x: CGFloat(20.0), y: CGFloat(10.0)))
}
func test_AppendTransform() {
let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
var identityTransform = AffineTransform.identity
identityTransform.append(identityTransform)
checkPointTransformation(identityTransform, point: point, expectedPoint: point)
let translate = AffineTransform(translationByX: 10.0, byY: 0.0)
let scale = AffineTransform(scale: 2.0)
var translateThenScale = translate
translateThenScale.append(scale)
checkPointTransformation(translateThenScale, point: point, expectedPoint: NSPoint(x: CGFloat(40.0), y: CGFloat(20.0)))
}
func test_PrependTransform() {
let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
var identityTransform = AffineTransform.identity
identityTransform.append(identityTransform)
checkPointTransformation(identityTransform, point: point, expectedPoint: point)
let translate = AffineTransform(translationByX: 10.0, byY: 0.0)
let scale = AffineTransform(scale: 2.0)
var scaleThenTranslate = translate
scaleThenTranslate.prepend(scale)
checkPointTransformation(scaleThenTranslate, point: point, expectedPoint: NSPoint(x: CGFloat(30.0), y: CGFloat(20.0)))
}
func test_TransformComposition() {
let origin = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0))
let size = NSSize(width: CGFloat(40.0), height: CGFloat(20.0))
let rect = NSRect(origin: origin, size: size)
let center = NSPoint(x: NSMidX(rect), y: NSMidY(rect))
let rotate = AffineTransform(rotationByDegrees: 90.0)
let moveOrigin = AffineTransform(translationByX: -center.x, byY: -center.y)
var moveBack = moveOrigin
moveBack.invert()
var rotateAboutCenter = rotate
rotateAboutCenter.prepend(moveOrigin)
rotateAboutCenter.append(moveBack)
// center of rect shouldn't move as its the rotation anchor
checkPointTransformation(rotateAboutCenter, point: center, expectedPoint: center)
}
func test_hashing_identity() {
let ref = NSAffineTransform()
let val = AffineTransform.identity
expectEqual(ref.hashValue, val.hashValue)
}
func test_hashing_values() {
// the transforms are made up and the values don't matter
let values = [
AffineTransform(m11: 1.0, m12: 2.5, m21: 66.2, m22: 40.2, tX: -5.5, tY: 3.7),
AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33),
AffineTransform(m11: 4.5, m12: 1.1, m21: 0.025, m22: 0.077, tX: -0.55, tY: 33.2),
AffineTransform(m11: 7.0, m12: -2.3, m21: 6.7, m22: 0.25, tX: 0.556, tY: 0.99),
AffineTransform(m11: 0.498, m12: -0.284, m21: -0.742, m22: 0.3248, tX: 12, tY: 44)
]
for val in values {
let ref = val as NSAffineTransform
expectEqual(ref.hashValue, val.hashValue)
}
}
func test_AnyHashableContainingAffineTransform() {
let values: [AffineTransform] = [
AffineTransform.identity,
AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33),
AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33)
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(AffineTransform.self, type(of: anyHashables[0].base))
expectEqual(AffineTransform.self, type(of: anyHashables[1].base))
expectEqual(AffineTransform.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
func test_AnyHashableCreatedFromNSAffineTransform() {
func makeNSAffineTransform(rotatedByDegrees angle: CGFloat) -> NSAffineTransform {
let result = NSAffineTransform()
result.rotate(byDegrees: angle)
return result
}
let values: [NSAffineTransform] = [
makeNSAffineTransform(rotatedByDegrees: 0),
makeNSAffineTransform(rotatedByDegrees: 10),
makeNSAffineTransform(rotatedByDegrees: 10),
]
let anyHashables = values.map(AnyHashable.init)
expectEqual(AffineTransform.self, type(of: anyHashables[0].base))
expectEqual(AffineTransform.self, type(of: anyHashables[1].base))
expectEqual(AffineTransform.self, type(of: anyHashables[2].base))
expectNotEqual(anyHashables[0], anyHashables[1])
expectEqual(anyHashables[1], anyHashables[2])
}
}
#if !FOUNDATION_XCTEST
var AffineTransformTests = TestSuite("TestAffineTransform")
AffineTransformTests.test("test_BasicConstruction") { TestAffineTransform().test_BasicConstruction() }
AffineTransformTests.test("test_IdentityTransformation") { TestAffineTransform().test_IdentityTransformation() }
AffineTransformTests.test("test_Translation") { TestAffineTransform().test_Translation() }
AffineTransformTests.test("test_Scale") { TestAffineTransform().test_Scale() }
AffineTransformTests.test("test_Rotation_Degrees") { TestAffineTransform().test_Rotation_Degrees() }
AffineTransformTests.test("test_Rotation_Radians") { TestAffineTransform().test_Rotation_Radians() }
AffineTransformTests.test("test_Inversion") { TestAffineTransform().test_Inversion() }
AffineTransformTests.test("test_TranslationComposed") { TestAffineTransform().test_TranslationComposed() }
AffineTransformTests.test("test_Scaling") { TestAffineTransform().test_Scaling() }
AffineTransformTests.test("test_TranslationScaling") { TestAffineTransform().test_TranslationScaling() }
AffineTransformTests.test("test_ScalingTranslation") { TestAffineTransform().test_ScalingTranslation() }
AffineTransformTests.test("test_AppendTransform") { TestAffineTransform().test_AppendTransform() }
AffineTransformTests.test("test_PrependTransform") { TestAffineTransform().test_PrependTransform() }
AffineTransformTests.test("test_TransformComposition") { TestAffineTransform().test_TransformComposition() }
AffineTransformTests.test("test_hashing_identity") { TestAffineTransform().test_hashing_identity() }
AffineTransformTests.test("test_hashing_values") { TestAffineTransform().test_hashing_values() }
AffineTransformTests.test("test_AnyHashableContainingAffineTransform") { TestAffineTransform().test_AnyHashableContainingAffineTransform() }
AffineTransformTests.test("test_AnyHashableCreatedFromNSAffineTransform") { TestAffineTransform().test_AnyHashableCreatedFromNSAffineTransform() }
runAllTests()
#endif
#endif
| apache-2.0 | 4b2a3742c0dcc9c8dd72e209d6e970c1 | 48.160305 | 171 | 0.663354 | 4.598905 | false | true | false | false |
tjw/swift | stdlib/public/core/UnicodeEncoding.swift | 6 | 4708 | //===--- UnicodeEncoding.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
//
//===----------------------------------------------------------------------===//
public protocol _UnicodeEncoding {
/// The basic unit of encoding
associatedtype CodeUnit : UnsignedInteger, FixedWidthInteger
/// A valid scalar value as represented in this encoding
associatedtype EncodedScalar : BidirectionalCollection
where EncodedScalar.Iterator.Element == CodeUnit
/// A unicode scalar value to be used when repairing
/// encoding/decoding errors, as represented in this encoding.
///
/// If the Unicode replacement character U+FFFD is representable in this
/// encoding, `encodedReplacementCharacter` encodes that scalar value.
static var encodedReplacementCharacter : EncodedScalar { get }
/// Converts from encoded to encoding-independent representation
static func decode(_ content: EncodedScalar) -> Unicode.Scalar
/// Converts from encoding-independent to encoded representation, returning
/// `nil` if the scalar can't be represented in this encoding.
static func encode(_ content: Unicode.Scalar) -> EncodedScalar?
/// Converts a scalar from another encoding's representation, returning
/// `nil` if the scalar can't be represented in this encoding.
///
/// A default implementation of this method will be provided
/// automatically for any conforming type that does not implement one.
static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar?
/// A type that can be used to parse `CodeUnits` into
/// `EncodedScalar`s.
associatedtype ForwardParser : Unicode.Parser
where ForwardParser.Encoding == Self
/// A type that can be used to parse a reversed sequence of
/// `CodeUnits` into `EncodedScalar`s.
associatedtype ReverseParser : Unicode.Parser
where ReverseParser.Encoding == Self
//===--------------------------------------------------------------------===//
// FIXME: this requirement shouldn't be here and is mitigated by the default
// implementation below. Compiler bugs prevent it from being expressed in an
// intermediate, underscored protocol.
/// Returns true if `x` only appears in this encoding as the representation of
/// a complete scalar value.
static func _isScalar(_ x: CodeUnit) -> Bool
}
extension _UnicodeEncoding {
// See note on declaration of requirement, above
@inlinable // FIXME(sil-serialize-all)
public static func _isScalar(_ x: CodeUnit) -> Bool { return false }
@inlinable // FIXME(sil-serialize-all)
public static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
return encode(FromEncoding.decode(content))
}
/// Converts from encoding-independent to encoded representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@inlinable // FIXME(sil-serialize-all)
internal static func _encode(_ content: Unicode.Scalar) -> EncodedScalar {
return encode(content) ?? encodedReplacementCharacter
}
/// Converts a scalar from another encoding's representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@inlinable // FIXME(sil-serialize-all)
internal static func _transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar {
return transcode(content, from: FromEncoding.self)
?? encodedReplacementCharacter
}
@inlinable // FIXME(sil-serialize-all)
internal static func _transcode<
Source: Sequence, SourceEncoding: Unicode.Encoding>(
_ source: Source,
from sourceEncoding: SourceEncoding.Type,
into processScalar: (EncodedScalar)->Void)
where Source.Element == SourceEncoding.CodeUnit {
var p = SourceEncoding.ForwardParser()
var i = source.makeIterator()
while true {
switch p.parseScalar(from: &i) {
case .valid(let e): processScalar(_transcode(e, from: sourceEncoding))
case .error(_): processScalar(encodedReplacementCharacter)
case .emptyInput: return
}
}
}
}
extension Unicode {
public typealias Encoding = _UnicodeEncoding
}
| apache-2.0 | 76fcff018b38def27bd0a6290074431f | 39.586207 | 80 | 0.700935 | 5.12854 | false | false | false | false |
takecian/SwiftRater | SwiftRater/UsageDataManager.swift | 1 | 7861 | //
// UsageDataManager.swift
// SwiftRater
//
// Created by Fujiki Takeshi on 2017/03/28.
// Copyright © 2017年 com.takecian. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
let SwiftRaterInvalid = -1
class UsageDataManager {
var daysUntilPrompt: Int = SwiftRaterInvalid
var usesUntilPrompt: Int = SwiftRaterInvalid
var significantUsesUntilPrompt: Int = SwiftRaterInvalid
var daysBeforeReminding: Int = SwiftRaterInvalid
var showLaterButton: Bool = true
var debugMode: Bool = false
var conditionsMetMode: SwiftRaterConditionsMetMode = .all
static private let keySwiftRaterFirstUseDate = "keySwiftRaterFirstUseDate"
static private let keySwiftRaterUseCount = "keySwiftRaterUseCount"
static private let keySwiftRaterSignificantEventCount = "keySwiftRaterSignificantEventCount"
static private let keySwiftRaterRateDone = "keySwiftRaterRateDone"
static private let keySwiftRaterTrackingVersion = "keySwiftRaterTrackingVersion"
static private let keySwiftRaterReminderRequestDate = "keySwiftRaterReminderRequestDate"
static var shared = UsageDataManager()
let userDefaults = UserDefaults.standard
private init() {
let defaults = [
UsageDataManager.keySwiftRaterFirstUseDate: 0,
UsageDataManager.keySwiftRaterUseCount: 0,
UsageDataManager.keySwiftRaterSignificantEventCount: 0,
UsageDataManager.keySwiftRaterRateDone: false,
UsageDataManager.keySwiftRaterTrackingVersion: "",
UsageDataManager.keySwiftRaterReminderRequestDate: 0
] as [String : Any]
let ud = UserDefaults.standard
ud.register(defaults: defaults)
}
var isRateDone: Bool {
get {
return userDefaults.bool(forKey: UsageDataManager.keySwiftRaterRateDone)
}
set {
userDefaults.set(newValue, forKey: UsageDataManager.keySwiftRaterRateDone)
userDefaults.synchronize()
}
}
var trackingVersion: String {
get {
return userDefaults.string(forKey: UsageDataManager.keySwiftRaterTrackingVersion) ?? ""
}
set {
userDefaults.set(newValue, forKey: UsageDataManager.keySwiftRaterTrackingVersion)
userDefaults.synchronize()
}
}
private var firstUseDate: TimeInterval {
get {
let value = userDefaults.double(forKey: UsageDataManager.keySwiftRaterFirstUseDate)
if value == 0 {
// store first launch date time
let firstLaunchTimeInterval = Date().timeIntervalSince1970
userDefaults.set(firstLaunchTimeInterval, forKey: UsageDataManager.keySwiftRaterFirstUseDate)
return firstLaunchTimeInterval
} else {
return value
}
}
}
private var reminderRequestToRate: TimeInterval {
get {
return userDefaults.double(forKey: UsageDataManager.keySwiftRaterReminderRequestDate)
}
set {
userDefaults.set(newValue, forKey: UsageDataManager.keySwiftRaterReminderRequestDate)
userDefaults.synchronize()
}
}
private var usesCount: Int {
get {
return userDefaults.integer(forKey: UsageDataManager.keySwiftRaterUseCount)
}
set {
userDefaults.set(newValue, forKey: UsageDataManager.keySwiftRaterUseCount)
userDefaults.synchronize()
}
}
private var significantEventCount: Int {
get {
return userDefaults.integer(forKey: UsageDataManager.keySwiftRaterSignificantEventCount)
}
set {
userDefaults.set(newValue, forKey: UsageDataManager.keySwiftRaterSignificantEventCount)
userDefaults.synchronize()
}
}
var ratingConditionsHaveBeenMet: Bool {
guard !debugMode else { // if debug mode, return always true
printMessage(message: " In debug mode")
return true
}
guard !isRateDone else { // if already rated, return false
printMessage(message: " Already rated")
return false }
var daysUntilPromptMet = false
var usesUntilPromptMet = false
var significantUsesUntilPromptMet = false
if reminderRequestToRate == 0 {
// check if the app has been used enough days
if daysUntilPrompt != SwiftRaterInvalid {
printMessage(message: " will check daysUntilPrompt")
let dateOfFirstLaunch = Date(timeIntervalSince1970: firstUseDate)
let timeSinceFirstLaunch = Date().timeIntervalSince(dateOfFirstLaunch)
let timeUntilRate = 60 * 60 * 24 * daysUntilPrompt
daysUntilPromptMet = Int(timeSinceFirstLaunch) > timeUntilRate
}
printMessage(message: "daysUntilPromptMet: \(daysUntilPromptMet) \(daysUntilPrompt == SwiftRaterInvalid ? "because daysUntilPromptMet is not set" : "")")
// check if the app has been used enough times
if usesUntilPrompt != SwiftRaterInvalid {
printMessage(message: " will check usesUntilPrompt")
usesUntilPromptMet = usesCount >= usesUntilPrompt
}
printMessage(message: "usesUntilPromptMet: \(usesUntilPromptMet) \(usesUntilPrompt == SwiftRaterInvalid ? "because usesUntilPrompt is not set" : "")")
// check if the user has done enough significant events
if significantUsesUntilPrompt != SwiftRaterInvalid {
printMessage(message: " will check significantUsesUntilPrompt")
significantUsesUntilPromptMet = significantEventCount >= significantUsesUntilPrompt
}
printMessage(message: "significantUsesUntilPromptMet: \(significantUsesUntilPromptMet) \(significantUsesUntilPrompt == SwiftRaterInvalid ? "because significantUsesUntilPrompt is not set" : "")")
} else {
// if the user wanted to be reminded later, has enough time passed?
if daysBeforeReminding != SwiftRaterInvalid {
printMessage(message: " will check daysBeforeReminding")
let dateOfReminderRequest = Date(timeIntervalSince1970: reminderRequestToRate)
let timeSinceReminderRequest = Date().timeIntervalSince(dateOfReminderRequest)
let timeUntilRate = 60 * 60 * 24 * daysBeforeReminding;
guard Int(timeSinceReminderRequest) < timeUntilRate else { return true }
}
}
if conditionsMetMode == .all {
return daysUntilPromptMet && usesUntilPromptMet && significantUsesUntilPromptMet
} else {
return daysUntilPromptMet || usesUntilPromptMet || significantUsesUntilPromptMet
}
}
func reset() {
userDefaults.set(0, forKey: UsageDataManager.keySwiftRaterFirstUseDate)
userDefaults.set(0, forKey: UsageDataManager.keySwiftRaterUseCount)
userDefaults.set(0, forKey: UsageDataManager.keySwiftRaterSignificantEventCount)
userDefaults.set(false, forKey: UsageDataManager.keySwiftRaterRateDone)
userDefaults.set(0, forKey: UsageDataManager.keySwiftRaterReminderRequestDate)
userDefaults.synchronize()
}
func incrementUseCount() {
usesCount = usesCount + 1
}
func incrementSignificantUseCount() {
significantEventCount = significantEventCount + 1
}
func saveReminderRequestDate() {
reminderRequestToRate = Date().timeIntervalSince1970
}
private func printMessage(message: String) {
if SwiftRater.showLog {
print("[SwiftRater] \(message)")
}
}
}
| mit | 94b159f8090a71a6a5542ac532c2b247 | 38.094527 | 206 | 0.662637 | 6.129485 | false | false | false | false |
sora0077/NicoKit | NicoKitDemo/SearchTableViewController.swift | 1 | 4413 | //
// SearchTableViewController.swift
// NicoKit
//
// Created by 林達也 on 2015/06/07.
// Copyright (c) 2015年 林達也. All rights reserved.
//
import UIKit
extension Search.Query.SortBy {
func title(order: Search.Query.Order) -> String {
switch self {
case .LastCommentTime:
switch order {
case .Desc:
return "コメントが新しい順"
case .Asc:
return "コメントが古い順"
}
case .ViewCounter:
switch order {
case .Desc:
return "再生が多い順"
case .Asc:
return "再生が少ない順"
}
case .StartTime:
switch order {
case .Desc:
return "投稿が新しい順"
case .Asc:
return "投稿が古い順"
}
case .MylistCounter:
switch order {
case .Desc:
return "マイリストが多い順"
case .Asc:
return "マイリストが少ない順"
}
case .CommentCounter:
switch order {
case .Desc:
return "コメントが多い順"
case .Asc:
return "コメントが少ない順"
}
case .LengthSeconds:
switch order {
case .Desc:
return "再生時間が長い順"
case .Asc:
return "再生時間が短い順"
}
}
}
}
class SearchTableViewController: UITableViewController {
@IBOutlet weak var textField: UITextField!
var keyword: String = ""
var searchTarget: Int = 0
var sort: Search.Query.SortBy = .LastCommentTime
var order: Search.Query.Order = .Desc
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func switchTargetAction(sender: UISegmentedControl) {
self.searchTarget = sender.selectedSegmentIndex
}
@IBAction func selectSortAction(sender: UIButton) {
let picker = UIAlertController(title: "", message: "", preferredStyle: .ActionSheet)
for s in Search.Query.SortBy.allValues {
picker.addAction(UIAlertAction(title: s.title(.Desc), style: .Default, handler: { [weak self] _ in
sender.setTitle(s.title(.Desc), forState: .Normal)
self?.sort = s
self?.order = .Desc
}))
picker.addAction(UIAlertAction(title: s.title(.Asc), style: .Default, handler: { [weak self] _ in
sender.setTitle(s.title(.Asc), forState: .Normal)
self?.sort = s
self?.order = .Asc
}))
}
picker.addAction(UIAlertAction(title: "キャンセル", style: .Cancel, handler: nil))
self.presentViewController(picker, animated: true, completion: nil)
}
@IBAction func searchAction(sender: AnyObject) {
self.keyword = self.textField.text
let type: Search.Query.SearchType
if self.searchTarget == 0 {
type = Search.Query.SearchType.Keyword(self.keyword)
} else {
type = Search.Query.SearchType.Tag(self.keyword)
}
var query = Search.Query(type: type)
query.sort_by = self.sort
query.order = self.order
let vc = from_storyboard(SearchResultViewController.self)
vc.query = query
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension SearchTableViewController: Storyboardable {
static var storyboardIdentifier: String {
return "SearchTableViewController"
}
static var storyboardName: String {
return "Main"
}
}
| mit | b5ae4da34e0fc3a7557b409ca3c841ea | 27.958621 | 113 | 0.551322 | 4.771591 | false | false | false | false |
iosexample/LearnSwift | YourFirstiOSApp/MyApp/MyApp/ViewController.swift | 1 | 1311 | //
// ViewController.swift
// MyApp
//
// Created by Dong on 16/7/16.
//
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var nameTextLabel: UILabel!
@IBOutlet weak var saveButton: UIBarButtonItem!
var item = Item?()
override func viewDidLoad() {
super.viewDidLoad()
if let item = item {
nameTextField.text = item.name
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if saveButton === sender {
let name = nameTextField.text ?? ""
item = Item(name: name)
}
}
// @IBAction func setLabelText(sender: AnyObject) {
// nameTextLabel.text = nameTextField.text
// }
@IBAction func cancel(sender: UIBarButtonItem) {
let isInAddMode = presentingViewController is UINavigationController
if isInAddMode {
dismissViewControllerAnimated(true, completion: nil)
}
else {
navigationController!.popViewControllerAnimated(true)
}
}
}
| apache-2.0 | 18aa753a8327d510ed80f76d32773573 | 22.836364 | 81 | 0.611747 | 5.141176 | false | false | false | false |
hackersatcambridge/hac-website | Sources/HaCWebsiteLib/Controllers/WorkshopsController.swift | 2 | 2903 | import Kitura
import HaCTML
struct WorkshopsController {
static var handler: RouterHandler = { request, response, next in
try response.send(
WorkshopsIndexPage(
allWorkshops: Array(WorkshopManager.workshops.values)
.sorted { $0.title < $1.title }
.filter { $0.workshopId != "example" }
).node.render()
).end()
}
static var workshopHandler: RouterHandler = { request, response, next in
if let workshopId = request.parameters["workshopId"],
let workshop = WorkshopManager.workshops[workshopId] {
try response.send(
IndividualWorkshopPage(workshop: workshop).node.render()
).end()
} else {
next()
}
}
static var workshopUpdateHandler: RouterHandler = { request, response, next in
WorkshopManager.update()
try response.send(
"Workshops updated!"
).end()
}
static var workshopVerifyHandler: RouterHandler = { request, response, next in
if let workshopId = request.parameters["workshopId"] {
let workshopURL = "https://github.com/hackersatcambridge/workshop-\(workshopId)"
// Run the parser
// Spit out the errors, or the workshop page if no errors
let repoUtil = GitUtil(
remoteRepoURL: workshopURL,
directoryName: "workshop-\(workshopId)"
)
print("Updating repo...")
repoUtil.update()
print("Finished updating")
let errorNode: Nodeable?
let pageNode: Nodeable?
do {
let workshop = try Workshop(localPath: repoUtil.localRepoPath, headCommitSha: repoUtil.getHeadCommitSha())
// MARK: Add warnings that probably indicate mistakes but are not validation errors
var warnings: [String] = []
if workshop.title == "Sample Workshop" { warnings.append("Title has not been set") }
if workshop.contributors.isEmpty { warnings.append("Contributors have not been listed") }
if warnings.isEmpty {
errorNode = El.Div[
Attr.className => "FlashMessage FlashMessage--positive"
].containing(
"Valid workshop repo!"
)
} else {
errorNode = El.Div[
Attr.className => "FlashMessage FlashMessage--minorNegative"
].containing(
El.Ul.containing(
warnings.map {
El.Li.containing("warning: \($0)")
}
)
)
}
pageNode = IndividualWorkshopPage(workshop: workshop)
} catch {
errorNode = El.Div[Attr.className => "FlashMessage FlashMessage--negative"].containing("error: \(error)")
pageNode = nil
}
try response.send(
Page(
title: "Workshop Validator: \(workshopId)",
content: Fragment([
errorNode,
pageNode
])
).render()
).end()
} else {
next()
}
}
}
| mit | 3bf15393384857eb235bed625310ab69 | 29.239583 | 114 | 0.599035 | 4.615262 | false | false | false | false |
nikrad/ios | FiveCalls/FiveCalls/AppDelegate.swift | 1 | 5682 | //
// AppDelegate.swift
// FiveCalls
//
// Created by Ben Scheirman on 1/30/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Pantry
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if isUITesting() {
resetData()
}
BuddyBuildSDK.setup()
Fabric.with([Crashlytics.self])
migrateSavedData()
Pantry.useApplicationSupportDirectory = true
clearNotificationBadge()
setAppearance()
if !UserDefaults.standard.bool(forKey: UserDefaultsKeys.hasShownWelcomeScreen.rawValue) {
showWelcome()
}
return true
}
func migrateSavedData() {
let pantryDirName = "com.thatthinginswift.pantry"
// Pantry used to store data in the caches folder. If this exists, we need to move it
// and delete it, to avoid this getting purged when the device is low on disk space.
let cachesDir = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
let oldPantryPath = URL(fileURLWithPath: cachesDir).appendingPathComponent(pantryDirName).path
if FileManager.default.fileExists(atPath: oldPantryPath) {
print("Saved data found in caches folder, moving to Application Support...")
let appSupportDir = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).first!
let targetPath = URL(fileURLWithPath: appSupportDir).appendingPathComponent(pantryDirName).path
do {
try FileManager.default.moveItem(atPath: oldPantryPath, toPath: targetPath)
print("Files migrated.")
} catch let e {
print("Error moving files: \(e)")
}
}
}
func transitionTo(rootViewController viewController: UIViewController) {
guard let window = self.window else { return }
guard window.rootViewController != viewController else { return }
let snapshot = window.snapshotView(afterScreenUpdates: false)!
viewController.view.addSubview(snapshot)
window.rootViewController = viewController
UIView.animate(withDuration: 0.5, animations: {
snapshot.alpha = 0
snapshot.frame.origin.y += window.frame.size.height
snapshot.transform = snapshot.transform.scaledBy(x: 0.8, y: 0.8)
}) { completed in
snapshot.removeFromSuperview()
}
}
func showWelcome() {
guard let window = self.window else { return }
let welcomeVC = R.storyboard.welcome.welcomeViewController()!
let mainVC = window.rootViewController!
welcomeVC.completionBlock = {
UserDefaults.standard.set(true, forKey: UserDefaultsKeys.hasShownWelcomeScreen.rawValue)
self.transitionTo(rootViewController: mainVC)
}
window.rootViewController = welcomeVC
}
func setAppearance() {
Appearance.instance.setup()
}
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 invalidate graphics rendering callbacks. 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 active 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:.
}
private func resetData() {
// clear user defaults
let appDomain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: appDomain)
// clear any saved location data
Pantry.removeAllCache()
}
private func clearNotificationBadge() {
UIApplication.shared.applicationIconBadgeNumber = 0
}
}
extension UIApplication {
func fvc_open(_ url: URL, completion: ((Bool) -> Void)? = nil) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url) {
completion?($0)
}
} else {
let result = UIApplication.shared.openURL(url)
completion?(result)
}
}
}
| mit | 7854feb4d35afd7da9b7eb553d040456 | 39.29078 | 285 | 0.679634 | 5.452015 | false | false | false | false |
badoo/Chatto | ChattoAdditions/sources/Input/Photos/Camera/LiveCameraCell.swift | 1 | 5330 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 AVFoundation
import Foundation
import UIKit
public struct LiveCameraCellAppearance {
public var backgroundColor: UIColor
public var cameraImageProvider: () -> UIImage?
public var cameraLockImageProvider: () -> UIImage?
public let accessibilityIdentifier = "chatto.inputbar.photos.cell.livecamera"
public init(backgroundColor: UIColor,
cameraImage: @autoclosure @escaping () -> UIImage?,
cameraLockImage: @autoclosure @escaping () -> UIImage?) {
self.backgroundColor = backgroundColor
self.cameraImageProvider = cameraImage
self.cameraLockImageProvider = cameraLockImage
}
public static func createDefaultAppearance() -> LiveCameraCellAppearance {
return LiveCameraCellAppearance(
backgroundColor: UIColor(red: 24.0/255.0, green: 101.0/255.0, blue: 245.0/255.0, alpha: 1),
cameraImage: UIImage(named: "camera", in: Bundle.resources, compatibleWith: nil),
cameraLockImage: UIImage(named: "camera_lock", in: Bundle.resources, compatibleWith: nil)
)
}
}
class LiveCameraCell: UICollectionViewCell {
private var iconImageView: UIImageView!
var appearance: LiveCameraCellAppearance = LiveCameraCellAppearance.createDefaultAppearance() {
didSet {
self.updateAppearance()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
private func commonInit() {
self.configureIcon()
self.contentView.backgroundColor = self.appearance.backgroundColor
}
var captureLayer: CALayer? {
didSet {
if oldValue !== self.captureLayer {
oldValue?.removeFromSuperlayer()
if let captureLayer = self.captureLayer {
self.contentView.layer.insertSublayer(captureLayer, below: self.iconImageView.layer)
let animation = CABasicAnimation.bma_fadeInAnimationWithDuration(0.25)
let animationKey = "fadeIn"
captureLayer.removeAnimation(forKey: animationKey)
captureLayer.add(animation, forKey: animationKey)
}
self.setNeedsLayout()
}
}
}
typealias CellCallback = (_ cell: LiveCameraCell) -> Void
var onWasAddedToWindow: CellCallback?
var onWasRemovedFromWindow: CellCallback?
override func didMoveToWindow() {
if self.window != nil {
self.onWasAddedToWindow?(self)
} else {
self.onWasRemovedFromWindow?(self)
}
}
func updateWithAuthorizationStatus(_ status: AVAuthorizationStatus) {
self.authorizationStatus = status
self.updateIcon()
}
private var authorizationStatus: AVAuthorizationStatus = .notDetermined
private func configureIcon() {
self.iconImageView = UIImageView()
self.iconImageView.contentMode = .center
self.contentView.addSubview(self.iconImageView)
}
private func updateAppearance() {
self.contentView.backgroundColor = self.appearance.backgroundColor
self.accessibilityIdentifier = self.appearance.accessibilityIdentifier
self.updateIcon()
}
private func updateIcon() {
switch self.authorizationStatus {
case .notDetermined, .authorized:
self.iconImageView.image = self.appearance.cameraImageProvider()
case .restricted, .denied:
self.iconImageView.image = self.appearance.cameraLockImageProvider()
@unknown default:
assertionFailure("Unsupported \(type(of: self.authorizationStatus)) case: \(self.authorizationStatus).")
self.iconImageView.image = self.appearance.cameraLockImageProvider()
}
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
self.captureLayer?.frame = self.contentView.bounds
self.iconImageView.sizeToFit()
self.iconImageView.center = self.contentView.bounds.bma_center
}
}
| mit | b4fc36cc0ff3e56a00c58b514f6e875c | 36.272727 | 116 | 0.68424 | 5.240905 | false | false | false | false |
wrutkowski/Lucid-Weather-Clock | Lucid Weather Clock/ColorManager.swift | 1 | 2526 | //
// ColorManager.swift
// Lucid Weather Clock
//
// Created by Wojciech Rutkowski on 09/12/15.
// Copyright © 2015 Wojciech Rutkowski. All rights reserved.
//
import Foundation
struct ColorMapSegment {
var temp: Float
var color: Color
}
struct Color {
var r: CGFloat
var g: CGFloat
var b: CGFloat
var toUIColor: UIColor {
return UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}
}
class ColorManager {
static let colorMap: [ColorMapSegment] = [
ColorMapSegment(temp: -30, color: Color(r: 38, g: 84, b: 114)),
ColorMapSegment(temp: -7, color: Color(r: 75, g: 168, b: 231)),
ColorMapSegment(temp: 0, color: Color(r: 115, g: 209, b: 239)),
ColorMapSegment(temp: 5, color: Color(r: 67, g: 205, b: 187)),
ColorMapSegment(temp: 18, color: Color(r: 251, g: 171, b: 48)),
ColorMapSegment(temp: 27, color: Color(r: 244, g: 119, b: 25)),
ColorMapSegment(temp: 50, color: Color(r: 254, g: 81, b: 12))
]
static func convertTemperatureToColor(_ temp: Float) -> Color {
var color = Color(r: 0, g: 0, b: 0)
for i in 0 ..< colorMap.count {
if temp <= colorMap[i].temp {
if i > 0 {
let bottomColorMap = colorMap[i - 1]
let topColorMap = colorMap[i]
color.r = bottomColorMap.color.r + ((topColorMap.color.r - bottomColorMap.color.r) / CGFloat(topColorMap.temp - bottomColorMap.temp)) * CGFloat(temp - bottomColorMap.temp)
color.g = bottomColorMap.color.g + ((topColorMap.color.g - bottomColorMap.color.g) / CGFloat(topColorMap.temp - bottomColorMap.temp)) * CGFloat(temp - bottomColorMap.temp)
color.b = bottomColorMap.color.b + ((topColorMap.color.b - bottomColorMap.color.b) / CGFloat(topColorMap.temp - bottomColorMap.temp)) * CGFloat(temp - bottomColorMap.temp)
break
} else {
// lowest temp
color.r = colorMap[i].color.r
color.g = colorMap[i].color.g
color.b = colorMap[i].color.b
break
}
} else if i == colorMap.count - 1 {
// highest temp
color.r = colorMap[i].color.r
color.g = colorMap[i].color.g
color.b = colorMap[i].color.b
}
}
return color
}
}
| mit | 00c93f70560d672172288790465afbb4 | 37.257576 | 191 | 0.54495 | 3.878648 | false | false | false | false |
quran/quran-ios | Sources/Caching/OperationCacheableService.swift | 1 | 2443 | //
// OperationCacheableService.swift
// Quran
//
// Created by Mohamed Afifi on 3/28/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import Locking
import PromiseKit
class OperationCacheableService<Input: Hashable, Output> {
private let cache: Cache<Input, Output>
private var inProgressOperations: [Input: Promise<Output>] = [:]
private let lock = NSLock()
private let operation: (Input) -> Promise<Output>
init(cache: Cache<Input, Output>, operation: @escaping (Input) -> Promise<Output>) {
self.cache = cache
self.operation = operation
}
func invalidate() {
lock.sync {
inProgressOperations.removeAll()
cache.removeAllObjects()
}
}
func get(_ input: Input) -> Promise<Output> {
lock.sync { () -> Promise<Output> in
if let result = cache.object(forKey: input) {
return Promise.value(result)
} else if let promise = inProgressOperations[input] {
return promise
} else {
// create the operation
let operationPromise = operation(input)
// add it to the in progress
inProgressOperations[input] = operationPromise
// cache the result
let promise = operationPromise.map { result -> Output in
self.lock.sync {
self.cache.setObject(result, forKey: input)
// remove from in progress
self.inProgressOperations.removeValue(forKey: input)
}
return result
}
return promise
}
}
}
func getCached(_ input: Input) -> Output? {
lock.sync {
cache.object(forKey: input)
}
}
}
| apache-2.0 | 49d4025937a98a26a585017caa6b670e | 31.144737 | 88 | 0.590667 | 4.762183 | false | false | false | false |
zapdroid/RXWeather | Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift | 1 | 1723 | import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan<T: Comparable>(_ expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return actual > expected
}
return false
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(_ expectedValue: NMBComparable?) -> NonNilMatcherFunc<NMBComparable> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be greater than <\(stringify(expectedValue))>"
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil && actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedDescending
return matches
}
}
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func > (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
#if _runtime(_ObjC)
extension NMBObjCMatcher {
public class func beGreaterThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
| mit | ace9a1ca70110edad3dbf47510d96c7e | 41.02439 | 121 | 0.700522 | 5.317901 | false | false | false | false |
svyatoslav-zubrin/Demo | swift/MulticontextCoreDataDemo/MulticontextCoreDataDemo/Classes/CoreDataStack/CoreDataManager.swift | 1 | 4514 | //
// CoreDataManager.swift
// MulticontextCoreDataDemo
//
// Created by Development on 10/16/14.
// Copyright (c) 2014 ___ZUBRIN___. All rights reserved.
//
import Foundation
import CoreData
class CoreDataManager: NSObject {
// MARK: - Singleton
class var sharedManager: CoreDataManager {
struct Static {
static var instance: CoreDataManager?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = CoreDataManager()
}
return Static.instance!
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.zubrin.MulticontextCoreDataDemo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("MulticontextCoreDataDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MulticontextCoreDataDemo.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
} | gpl-2.0 | ae9318964e26c087e4977941201eb3eb | 49.166667 | 290 | 0.681436 | 5.794608 | false | false | false | false |
wyp767363905/GiftSay | GiftSay/GiftSay/classes/giftSay/adDetail/view/PostWebCell.swift | 1 | 2281 | //
// PostWebCell.swift
// GiftSay
//
// Created by qianfeng on 16/8/28.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
protocol PostWebCellDelegate: NSObjectProtocol {
func heightForRow(height: CGFloat)
}
class PostWebCell: UITableViewCell {
weak var delegate: PostWebCellDelegate?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var webView: UIWebView!
var dataModel: ADPostDataModel?{
didSet {
showData()
}
}
func showData(){
titleLabel.text = dataModel?.title
let url = NSURL(string: (dataModel?.content_url)!)
let request = NSURLRequest(URL: url!)
webView.delegate = self
webView.scrollView.scrollEnabled = false
webView.loadRequest(request)
}
class func createPostWebCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, withDataModel dataModel: ADPostDataModel, delegate: PostWebCellDelegate?) -> PostWebCell {
let cellId = "postWebCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? PostWebCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("PostWebCell", owner: nil, options: nil).last as? PostWebCell
}
cell?.dataModel = dataModel
cell?.delegate = delegate
cell?.updateFocusIfNeeded()
return cell!
}
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
}
}
extension PostWebCell : UIWebViewDelegate {
func webViewDidFinishLoad(webView: UIWebView) {
let webHeightStr = webView.stringByEvaluatingJavaScriptFromString("document.body.scrollHeight")
let height = CGFloat((webHeightStr! as NSString).floatValue)
delegate?.heightForRow(CGFloat(height))
}
}
| mit | 25e271f7595666142f7c996ca4dc59e4 | 21.333333 | 186 | 0.593942 | 5.583333 | false | false | false | false |
AngryLi/ResourceSummary | iOS/Demos/Assignments_swift/assignment-2-wechat/1252929_李亚洲_WechatSwift/WechatDemo/LsSendView.swift | 3 | 4289 | //
// SendView.swift
// WechatDemo
//
// Created by 李亚洲 on 15/5/19.
// Copyright (c) 2015年 Ming Wang. All rights reserved.
//
import UIKit
import Foundation
protocol SendViewdelegate : class
{
func sendMessage(view:LsSendView, message: Message,scene : WXScene)
func imageSelect()
}
extension UITextField
{
func addLeftBlank(#width : CGFloat, color : UIColor)
{
var leftFrame = self.bounds
leftFrame.size.width = width
self.leftView = UIView(frame: leftFrame)
self.leftView?.backgroundColor = color
self.leftViewMode = UITextFieldViewMode.Always
}
func addRightBlank(#width : CGFloat, color : UIColor)
{
var leftFrame = self.bounds
leftFrame.size.width = width
leftFrame.origin.x = self.bounds.size.width - width
self.rightView = UIView(frame: leftFrame)
self.rightView?.backgroundColor = color
self.rightViewMode = UITextFieldViewMode.Always
}
}
class LsSendView: UIView
{
weak var delegate : SendViewdelegate?
//MARK: 添加的控件
var contentField : UITextField?
var sendBtn : UIButton?
var imageBtn : UIButton?
var timeLineBtn : UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
var btnW :CGFloat = 40
var btnH :CGFloat = 30
var marginX : CGFloat = 2
var btnX :CGFloat = self.frame.size.width - btnW
var btnY :CGFloat = (self.frame.size.height - btnH) * 0.5
contentField = UITextField(frame: CGRectMake(0, btnY, self.bounds.size.width - btnW - 2 * btnH - 3 * marginX, btnH))
contentField!.addLeftBlank(width: 10, color: UIColor.clearColor())
contentField!.addRightBlank(width: 10, color: UIColor.clearColor())
contentField!.layer.cornerRadius = 10
contentField!.layer.borderWidth = 1
// contentField!.backgroundColor = UIColor.yellowColor()
self.addSubview(contentField!)
imageBtn = UIButton(frame: CGRectMake(contentField!.frame.maxX + marginX, btnY, btnH, btnH))
// imageBtn?.backgroundColor = UIColor.redColor()
imageBtn?.setImage(UIImage(named: "pic"), forState: UIControlState.Normal)
imageBtn?.addTarget(self, action: "imageSelect", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(imageBtn!)
timeLineBtn = UIButton(frame: CGRectMake(imageBtn!.frame.maxX + marginX, btnY, btnH, btnH))
timeLineBtn?.setImage(UIImage(named: "timeline"), forState: UIControlState.Normal)
timeLineBtn!.addTarget(self, action: "timeLineBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(timeLineBtn!)
sendBtn = UIButton(frame: CGRectMake(btnX, btnY, btnW, btnH))
sendBtn!.layer.cornerRadius = 10
sendBtn!.setTitle("发送", forState: UIControlState.Normal)
sendBtn!.setTitle("草", forState: UIControlState.Highlighted)
sendBtn!.backgroundColor = UIColor.grayColor()
sendBtn!.addTarget(self, action: "sendBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(sendBtn!)
}
func sendBtnClick()
{
if contentField!.text.isEmpty
{
sendMessage(Message(newContent: nil, newImage: nil),scene : WXSceneSession)
}
else
{
sendMessage(Message(newContent: contentField!.text, newImage: nil),scene : WXSceneSession)
}
contentField?.text = String()
}
func timeLineBtnClick()
{
if contentField!.text.isEmpty
{
sendMessage(Message(newContent: nil, newImage: nil),scene : WXSceneTimeline)
}
else
{
sendMessage(Message(newContent: contentField!.text, newImage: nil),scene : WXSceneTimeline)
}
}
func imageSelect()
{
self.delegate?.imageSelect()
}
func sendMessage(message : Message,scene : WXScene)
{
self.delegate?.sendMessage(self, message: message,scene : scene)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| mit | 18706c7cea9ab250bef16b0826186a67 | 33.12 | 124 | 0.643845 | 4.581096 | false | false | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_C001_DecomposingArrays.playground/section-2.swift | 2 | 1761 | import UIKit
/*
// Decomposing Arrays
//
// Suggested Reading:
// http://www.objc.io/snippets/1.html
// http://www.objc.io/snippets/10.html
/===================================*/
/*------------------------------------/
// Head : Tail
/------------------------------------*/
extension Array {
var decompose: (head: T, tail: [T])? {
return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}
}
func sum(xs: [Int]) -> Int {
if let (head, tail) = xs.decompose {
return head + sum(tail)
} else {
return 0
}
}
sum([5])
sum([1, 2, 3])
sum([])
/*------------------------------------/
// Quicksort
/------------------------------------*/
func qsort (var input: [Int]) -> [Int] {
if let (pivot, rest) = input.decompose {
let lesser = rest.filter { $0 < pivot }
let greater = rest.filter { $0 > pivot }
return qsort(lesser) + [pivot] + qsort(greater)
} else {
return []
}
}
qsort([42, 34, 100, 1, 3])
/*------------------------------------/
// Permutations
/------------------------------------*/
func between<T>(x: T, ys: [T]) -> [[T]] {
if let (head, tail) = ys.decompose {
return [[x] + ys] + between(x, tail).map { [head] + $0 }
} else {
return [[x]]
}
}
// All possible ways to insert an element into an array
let betweenResult = between(0, [1, 2, 3])
betweenResult
// Need the flat map operator
infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
return xs.map(f).reduce([], combine: +)
}
// Now create permutations
func permutations<T>(xs: [T]) -> [[T]] {
if let (head, tail) = xs.decompose {
return permutations(tail) >>= { permTail in
between(head, permTail)
}
} else {
return [[]]
}
}
let permutationResult = permutations([1, 2, 3])
| gpl-3.0 | c00658dd09af4d99da6db5682bfe922a | 19.476744 | 64 | 0.475298 | 3.255083 | false | false | false | false |
sanjaymhj/ChatOverLapView | HChatHeads/Views/BorderedRoundView.swift | 1 | 2250 | import UIKit
class BorderedRoundView: UIView {
private var imageView: RoundImageView?
private var borderWidth: CGFloat?
private var borderColor: CGColor?
convenience init(frame: CGRect, image: UIImage, borderWidth: Float, borderColor: UIColor) {
let viewFrame = CGRect(x: CGRectGetMinX(frame), y: CGRectGetMinY(frame), width: frame.width, height: frame.height)
self.init(frame: viewFrame)
self.borderWidth = CGFloat(borderWidth)
self.borderColor = borderColor.CGColor
self.backgroundColor = borderColor
initImageView(image)
}
private func initImageView(image: UIImage) {
self.imageView = RoundImageView(frame: CGRectZero)
self.imageView!.image = image
self.imageView?.backgroundColor = UIColor.clearColor()
self.imageView!.clipsToBounds = true
self.imageView!.contentMode = .ScaleAspectFill
self.addSubview(self.imageView!)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
changeToSquareShape()
createRoundBorder()
let imageViewFrame = CGRect(x: CGRectGetMinX(self.bounds) + CGFloat(self.borderWidth!),
y: CGRectGetMinY(self.bounds) + CGFloat(self.borderWidth!),
width: self.frame.width - 2 * CGFloat(self.borderWidth!),
height: self.frame.height - 2 * CGFloat(self.borderWidth!))
self.imageView?.frame = imageViewFrame
}
//MARK:- Change to Square and Round
private func changeToSquareShape() {
self.frame = squareShape(fromFrame: self.frame)
}
private func squareShape(fromFrame rect: CGRect) -> CGRect {
let minDimension = min(rect.size.height, rect.size.width)
var newRect = rect
newRect.size.width = minDimension
newRect.size.height = minDimension
return newRect
}
private func createRoundBorder() {
self.layer.cornerRadius = self.frame.width / 2
}
}
| mit | 31aca8f3167963de4d7451ec55ee9f6c | 34.15625 | 122 | 0.626667 | 4.912664 | false | false | false | false |
tangplin/JSON2Anything | JSON2Anything/Source/J2AInvocation.swift | 1 | 4345 | //
// J2AInvocation.swift
//
// Copyright (c) 2014 Pinglin Tang
//
// 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 UIKit
extension J2AInvocation {
/*
* Set the Arguments in JSON Array
*/
func setArgumentsWithArgumentsJSON(argumentsJSON: [AnyObject]){
for index in 0 ..< argumentsJSON.count {
if let subJSON = argumentsJSON[index] as? Dictionary<String, [AnyObject]> {
for (subAnyName, subArrayJson) in subJSON {
let cType = self.methodSignature().getArgumentTypeAtIndex(2+index)
if let argumentType:String = String.fromCString(cType) {
switch argumentType {
case "@":
if var object: AnyObject = objectWithClassName(subAnyName,methodsJSON:subArrayJson) {
self.setArgument(&object,atIndex:2+index)
}
case "c","i","s","l","C","I","S","L","q","Q":
var int = Int.anythingWithJSON(subArrayJson)
self.setArgument(&int,atIndex:2+index)
case "f":
var float = Float.anythingWithJSON(subArrayJson)
self.setArgument(&float,atIndex:2+index)
case "d":
var double = Double.anythingWithJSON(subArrayJson)
self.setArgument(&double,atIndex:2+index)
case "B":
var bool = Bool.anythingWithJSON(subArrayJson)
self.setArgument(&bool,atIndex:2+index)
case let type where type.hasPrefix("{CGRect="):
var rect = CGRect.anythingWithJSON(subArrayJson)
self.setArgument(&rect,atIndex:2+index)
case let type where type.hasPrefix("{CGSize="):
var size = CGSize.anythingWithJSON(subArrayJson)
self.setArgument(&size,atIndex:2+index)
case let type where type.hasPrefix("{CGPoint="):
var point = CGPoint.anythingWithJSON(subArrayJson)
self.setArgument(&point,atIndex:2+index)
default:
println("miss the type:\(argumentType)")
}
}
break
}
}
}
}
/*
* return the invocation waiting for `invoke`
*/
class func invocationWithTarget(target: AnyObject, selector: Selector, argumentsJSON: [AnyObject]) -> Self?{
if let signature = target.methodSignatureForSelector(selector) {
let invocation = self(methodSignature:signature)
let numberOfArguments = signature.numberOfArguments
if numberOfArguments == 2 + argumentsJSON.count {
invocation.setSelector(selector)
invocation.setTarget(target)
invocation.retainArguments()
invocation.setArgumentsWithArgumentsJSON(argumentsJSON)
return invocation;
}
}
return nil
}
} | mit | 62afbd766758ee20e53f2f4cf6b53612 | 46.23913 | 113 | 0.56985 | 5.451694 | false | false | false | false |
airspeedswift/swift | test/AutoDiff/Sema/differentiable_attr_type_checking.swift | 3 | 23108 | // RUN: %target-swift-frontend-typecheck -verify -disable-availability-checking %s
import _Differentiation
// Dummy `Differentiable`-conforming type.
public struct DummyTangentVector: Differentiable & AdditiveArithmetic {
public static var zero: Self { Self() }
public static func + (_: Self, _: Self) -> Self { Self() }
public static func - (_: Self, _: Self) -> Self { Self() }
public typealias TangentVector = Self
}
@differentiable // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
let globalConst: Float = 1
@differentiable // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
var globalVar: Float = 1
func testLocalVariables() {
// expected-error @+1 {{'_' has no parameters to differentiate with respect to}}
@differentiable
var getter: Float {
return 1
}
// expected-error @+1 {{'_' has no parameters to differentiate with respect to}}
@differentiable
var getterSetter: Float {
get { return 1 }
set {}
}
}
@differentiable // expected-error {{'@differentiable' attribute cannot be applied to this declaration}}
protocol P {}
@differentiable() // ok!
func no_jvp_or_vjp(_ x: Float) -> Float {
return x * x
}
// Test duplicate `@differentiable` attributes.
@differentiable // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable // expected-note {{other attribute declared here}}
func dupe_attributes(arg: Float) -> Float { return arg }
@differentiable(wrt: arg1)
@differentiable(wrt: arg2) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(wrt: arg2) // expected-note {{other attribute declared here}}
func dupe_attributes(arg1: Float, arg2: Float) -> Float { return arg1 }
struct ComputedPropertyDupeAttributes<T: Differentiable>: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
var value: T
@differentiable // expected-note {{other attribute declared here}}
var computed1: T {
@differentiable // expected-error {{duplicate '@differentiable' attribute with same parameters}}
get { value }
set { value = newValue }
}
// TODO(TF-482): Remove diagnostics when `@differentiable` attributes are
// also uniqued based on generic requirements.
@differentiable(where T == Float) // expected-error {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(where T == Double) // expected-note {{other attribute declared here}}
var computed2: T {
get { value }
set { value = newValue }
}
}
// Test TF-568.
protocol WrtOnlySelfProtocol: Differentiable {
@differentiable
var computedProperty: Float { get }
@differentiable
func method() -> Float
}
class Class: Differentiable {
typealias TangentVector = DummyTangentVector
func move(along _: TangentVector) {}
}
@differentiable(wrt: x)
func invalidDiffWrtClass(_ x: Class) -> Class {
return x
}
protocol Proto {}
// expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'Proto' does not conform to 'Differentiable'}}
@differentiable(wrt: x)
func invalidDiffWrtExistential(_ x: Proto) -> Proto {
return x
}
// expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '@differentiable (Float) -> Float' does not conform to 'Differentiable'}}
@differentiable(wrt: fn)
func invalidDiffWrtFunction(_ fn: @differentiable(Float) -> Float) -> Float {
return fn(.pi)
}
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable
func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable
func invalidDiffVoidResult(x: Float) {}
// Test static methods.
struct StaticMethod {
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable
static func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable
static func invalidDiffVoidResult(x: Float) {}
}
// Test instance methods.
struct InstanceMethod {
// expected-error @+1 {{'invalidDiffNoParams()' has no parameters to differentiate with respect to}}
@differentiable
func invalidDiffNoParams() -> Float {
return 1
}
// expected-error @+1 {{cannot differentiate void function 'invalidDiffVoidResult(x:)'}}
@differentiable
func invalidDiffVoidResult(x: Float) {}
}
// Test instance methods for a `Differentiable` type.
struct DifferentiableInstanceMethod: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
@differentiable // ok
func noParams() -> Float {
return 1
}
}
// Test subscript methods.
struct SubscriptMethod: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
@differentiable // ok
subscript(implicitGetter x: Float) -> Float {
return x
}
@differentiable // ok
subscript(implicitGetterSetter x: Float) -> Float {
get { return x }
set {}
}
subscript(explicit x: Float) -> Float {
@differentiable // ok
get { return x }
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable
set {}
}
subscript(x: Float, y: Float) -> Float {
@differentiable // ok
get { return x + y }
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable
set {}
}
}
// expected-error @+3 {{type 'Scalar' constrained to non-protocol, non-class type 'Float'}}
// expected-error @+2 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
// expected-note @+1 {{use 'Scalar == Float' to require 'Scalar' to be 'Float'}}
@differentiable(where Scalar: Float)
func invalidRequirementConformance<Scalar>(x: Scalar) -> Scalar {
return x
}
@differentiable(where T: AnyObject)
func invalidAnyObjectRequirement<T: Differentiable>(x: T) -> T {
return x
}
// expected-error @+1 {{'@differentiable' attribute does not yet support layout requirements}}
@differentiable(where Scalar: _Trivial)
func invalidRequirementLayout<Scalar>(x: Scalar) -> Scalar {
return x
}
// expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
@differentiable
func missingConformance<T>(_ x: T) -> T {
return x
}
protocol ProtocolRequirements: Differentiable {
// expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Float)'}}
@differentiable
init(x: Float, y: Float)
// expected-note @+2 {{protocol requires initializer 'init(x:y:)' with type '(x: Float, y: Int)'}}
@differentiable(wrt: x)
init(x: Float, y: Int)
// expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Float) -> Float';}}
@differentiable
func amb(x: Float, y: Float) -> Float
// expected-note @+2 {{protocol requires function 'amb(x:y:)' with type '(Float, Int) -> Float';}}
@differentiable(wrt: x)
func amb(x: Float, y: Int) -> Float
// expected-note @+3 {{protocol requires function 'f1'}}
// expected-note @+2 {{overridden declaration is here}}
@differentiable(wrt: (self, x))
func f1(_ x: Float) -> Float
// expected-note @+2 {{protocol requires function 'f2'}}
@differentiable(wrt: (self, x, y))
func f2(_ x: Float, _ y: Float) -> Float
}
protocol ProtocolRequirementsRefined: ProtocolRequirements {
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable'}}
func f1(_ x: Float) -> Float
}
// Test missing `@differentiable` attribute for internal protocol witnesses.
// No errors expected; internal `@differentiable` attributes are created.
struct InternalDiffAttrConformance: ProtocolRequirements {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
var x: Float
var y: Float
init(x: Float, y: Float) {
self.x = x
self.y = y
}
init(x: Float, y: Int) {
self.x = x
self.y = Float(y)
}
func amb(x: Float, y: Float) -> Float {
return x
}
func amb(x: Float, y: Int) -> Float {
return x
}
func f1(_ x: Float) -> Float {
return x
}
@differentiable(wrt: (self, x))
func f2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
// Test missing `@differentiable` attribute for public protocol witnesses. Errors expected.
// expected-error @+1 {{does not conform to protocol 'ProtocolRequirements'}}
public struct PublicDiffAttrConformance: ProtocolRequirements {
public typealias TangentVector = DummyTangentVector
public mutating func move(along _: TangentVector) {}
var x: Float
var y: Float
// FIXME(TF-284): Fix unexpected diagnostic.
// expected-note @+2 {{candidate is missing attribute '@differentiable'}} {{10-10=@differentiable }}
// expected-note @+1 {{candidate has non-matching type '(x: Float, y: Float)'}}
public init(x: Float, y: Float) {
self.x = x
self.y = y
}
// FIXME(TF-284): Fix unexpected diagnostic.
// expected-note @+2 {{candidate is missing attribute '@differentiable'}} {{10-10=@differentiable }}
// expected-note @+1 {{candidate has non-matching type '(x: Float, y: Int)'}}
public init(x: Float, y: Int) {
self.x = x
self.y = Float(y)
}
// expected-note @+2 {{candidate is missing attribute '@differentiable'}} {{10-10=@differentiable }}
// expected-note @+1 {{candidate has non-matching type '(Float, Float) -> Float'}}
public func amb(x: Float, y: Float) -> Float {
return x
}
// expected-note @+2 {{candidate is missing attribute '@differentiable(wrt: x)'}} {{10-10=@differentiable(wrt: x) }}
// expected-note @+1 {{candidate has non-matching type '(Float, Int) -> Float'}}
public func amb(x: Float, y: Int) -> Float {
return x
}
// expected-note @+1 {{candidate is missing attribute '@differentiable'}}
public func f1(_ x: Float) -> Float {
return x
}
// expected-note @+2 {{candidate is missing attribute '@differentiable'}}
@differentiable(wrt: (self, x))
public func f2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
protocol ProtocolRequirementsWithDefault_NoConformingTypes {
@differentiable
func f1(_ x: Float) -> Float
}
extension ProtocolRequirementsWithDefault_NoConformingTypes {
// TODO(TF-650): It would be nice to diagnose protocol default implementation
// with missing `@differentiable` attribute.
func f1(_ x: Float) -> Float { x }
}
protocol ProtocolRequirementsWithDefault {
@differentiable
func f1(_ x: Float) -> Float
}
extension ProtocolRequirementsWithDefault {
func f1(_ x: Float) -> Float { x }
}
struct DiffAttrConformanceErrors2: ProtocolRequirementsWithDefault {
func f1(_ x: Float) -> Float { x }
}
protocol NotRefiningDiffable {
@differentiable(wrt: x)
func a(_ x: Float) -> Float
}
struct CertainlyNotDiffableWrtSelf: NotRefiningDiffable {
func a(_ x: Float) -> Float { return x * 5.0 }
}
protocol TF285: Differentiable {
@differentiable(wrt: (x, y))
@differentiable(wrt: x)
func foo(x: Float, y: Float) -> Float
}
struct TF285MissingOneDiffAttr: TF285 {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
// Requirement is missing the required `@differentiable(wrt: (x, y))` attribute.
// Since `TF285MissingOneDiffAttr.foo` is internal, the attribute is implicitly created.
@differentiable(wrt: x)
func foo(x: Float, y: Float) -> Float {
return x
}
}
// TF-521: Test invalid `@differentiable` attribute due to invalid
// `Differentiable` conformance (`TangentVector` does not conform to
// `AdditiveArithmetic`).
struct TF_521<T: FloatingPoint> {
var real: T
var imaginary: T
// expected-error @+1 {{can only differentiate functions with results that conform to 'Differentiable', but 'TF_521<T>' does not conform to 'Differentiable'}}
@differentiable(where T: Differentiable, T == T.TangentVector)
init(real: T = 0, imaginary: T = 0) {
self.real = real
self.imaginary = imaginary
}
}
// expected-error @+1 {{type 'TF_521<T>' does not conform to protocol 'Differentiable'}}
extension TF_521: Differentiable where T: Differentiable {
// expected-note @+1 {{possibly intended match 'TF_521<T>.TangentVector' does not conform to 'AdditiveArithmetic'}}
typealias TangentVector = TF_521
}
// expected-error @+1 {{result type 'TF_521<Float>' does not conform to 'Differentiable', but the enclosing function type is '@differentiable'}}
let _: @differentiable(Float, Float) -> TF_521<Float> = { r, i in
TF_521(real: r, imaginary: i)
}
// TF-296: Infer `@differentiable` wrt parameters to be to all parameters that conform to `Differentiable`.
@differentiable
func infer1(_ a: Float, _ b: Int) -> Float {
return a + Float(b)
}
@differentiable
func infer2(_ fn: @differentiable(Float) -> Float, x: Float) -> Float {
return fn(x)
}
struct DiffableStruct: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
var a: Float
@differentiable
func fn(_ b: Float, _ c: Int) -> Float {
return a + b + Float(c)
}
}
struct NonDiffableStruct {
var a: Float
@differentiable
func fn(_ b: Float) -> Float {
return a + b
}
}
// Index based 'wrt:'
struct NumberWrtStruct: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
var a, b: Float
@differentiable(wrt: 0) // ok
@differentiable(wrt: 1) // ok
func foo1(_ x: Float, _ y: Float) -> Float {
return a*x + b*y
}
@differentiable(wrt: -1) // expected-error {{expected a parameter, which can be a function parameter name, parameter index, or 'self'}}
@differentiable(wrt: (1, x)) // expected-error {{parameters must be specified in original order}}
func foo2(_ x: Float, _ y: Float) -> Float {
return a*x + b*y
}
@differentiable(wrt: (x, 1)) // ok
@differentiable(wrt: (0)) // ok
static func staticFoo1(_ x: Float, _ y: Float) -> Float {
return x + y
}
@differentiable(wrt: (1, 1)) // expected-error {{parameters must be specified in original order}}
@differentiable(wrt: (2)) // expected-error {{parameter index is larger than total number of parameters}}
static func staticFoo2(_ x: Float, _ y: Float) -> Float {
return x + y
}
}
@differentiable(wrt: y) // ok
func two1(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (x, y)) // ok
func two2(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (0, y)) // ok
func two3(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (x, 1)) // ok
func two4(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (0, 1)) // ok
func two5(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: 2) // expected-error {{parameter index is larger than total number of parameters}}
func two6(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (1, 0)) // expected-error {{parameters must be specified in original order}}
func two7(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (1, x)) // expected-error {{parameters must be specified in original order}}
func two8(x: Float, y: Float) -> Float {
return x + y
}
@differentiable(wrt: (y, 0)) // expected-error {{parameters must be specified in original order}}
func two9(x: Float, y: Float) -> Float {
return x + y
}
// Inout 'wrt:' arguments.
@differentiable(wrt: y)
func inout1(x: Float, y: inout Float) -> Void {
let _ = x + y
}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(wrt: y)
func inout2(x: Float, y: inout Float) -> Float {
let _ = x + y
}
// Test refining protocol requirements with `@differentiable` attribute.
public protocol Distribution {
associatedtype Value
func logProbability(of value: Value) -> Float
}
public protocol DifferentiableDistribution: Differentiable, Distribution {
// expected-note @+2 {{overridden declaration is here}}
@differentiable(wrt: self)
func logProbability(of value: Value) -> Float
}
// Adding a more general `@differentiable` attribute.
public protocol DoubleDifferentiableDistribution: DifferentiableDistribution
where Value: Differentiable {
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable(wrt: self)'}} {{3-3=@differentiable(wrt: self) }}
func logProbability(of value: Value) -> Float
}
// Test failure to satisfy protocol requirement's `@differentiable` attribute.
public protocol HasRequirement {
@differentiable
// expected-note @+1 {{protocol requires function 'requirement' with type '<T> (T, T) -> T'; do you want to add a stub?}}
func requirement<T: Differentiable>(_ x: T, _ y: T) -> T
}
// expected-error @+1 {{type 'AttemptsToSatisfyRequirement' does not conform to protocol 'HasRequirement'}}
public struct AttemptsToSatisfyRequirement: HasRequirement {
// This `@differentiable` attribute does not satisfy the requirement because
// it is mroe constrained than the requirement's `@differentiable` attribute.
@differentiable(where T: CustomStringConvertible)
// expected-note @+1 {{candidate is missing attribute '@differentiable(wrt: (x, y))'}}
public func requirement<T: Differentiable>(_ x: T, _ y: T) -> T { x }
}
// Test protocol requirement `@differentiable` attribute unsupported features.
protocol ProtocolRequirementUnsupported: Differentiable {
associatedtype Scalar
// expected-error @+1 {{'@differentiable' attribute on protocol requirement cannot specify 'where' clause}}
@differentiable(where Scalar: Differentiable)
func unsupportedWhereClause(value: Scalar) -> Float
}
extension ProtocolRequirementUnsupported {
func dfoo(_ x: Float) -> (Float, (Float) -> Float) {
(x, { $0 })
}
}
// Classes.
class Super: Differentiable {
typealias TangentVector = DummyTangentVector
func move(along _: TangentVector) {}
var base: Float
// expected-error @+1 {{'@differentiable' attribute cannot be declared on 'init' in a non-final class; consider making 'Super' final}}
@differentiable
init(base: Float) {
self.base = base
}
// NOTE(TF-1040): `@differentiable` attribute on class methods currently
// does two orthogonal things:
// - Requests derivative generation for the class method.
// - Adds JVP/VJP vtable entries for the class method.
// There's currently no way using `@differentiable` to do only one of the
// above.
@differentiable
func testClassMethod(_ x: Float) -> Float { x }
@differentiable
final func testFinalMethod(_ x: Float) -> Float { x }
@differentiable
static func testStaticMethod(_ x: Float) -> Float { x }
@differentiable(wrt: (self, x))
@differentiable(wrt: x)
// expected-note @+1 2 {{overridden declaration is here}}
func testMissingAttributes(_ x: Float) -> Float { x }
@differentiable(wrt: x)
func testSuperclassDerivatives(_ x: Float) -> Float { x }
// Test duplicate attributes with different derivative generic signatures.
// expected-error @+1 {{duplicate '@differentiable' attribute with same parameters}}
@differentiable(wrt: x where T: Differentiable)
// expected-note @+1 {{other attribute declared here}}
@differentiable(wrt: x)
func instanceMethod<T>(_ x: Float, y: T) -> Float { x }
// expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}}
@differentiable
func dynamicSelfResult() -> Self { self }
// expected-error @+1 {{'@differentiable' attribute cannot be declared on class members returning 'Self'}}
@differentiable
var testDynamicSelfProperty: Self { self }
// TODO(TF-632): Fix "'TangentVector' is not a member type of 'Self'" diagnostic.
// The underlying error should appear instead:
// "covariant 'Self' can only appear at the top level of method result type".
// expected-error @+1 2 {{'TangentVector' is not a member type of 'Self'}}
func vjpDynamicSelfResult() -> (Self, (Self.TangentVector) -> Self.TangentVector) {
return (self, { $0 })
}
}
class Sub: Super {
// expected-error @+2 {{overriding declaration is missing attribute '@differentiable(wrt: x)'}}
// expected-error @+1 {{overriding declaration is missing attribute '@differentiable'}}
override func testMissingAttributes(_ x: Float) -> Float { x }
}
final class FinalClass: Differentiable {
typealias TangentVector = DummyTangentVector
func move(along _: TangentVector) {}
var base: Float
@differentiable
init(base: Float) {
self.base = base
}
}
// Test `inout` parameters.
@differentiable(wrt: y)
func inoutVoid(x: Float, y: inout Float) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable
func multipleSemanticResults(_ x: inout Float) -> Float { x }
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable(wrt: y)
func swap(x: inout Float, y: inout Float) {}
struct InoutParameters: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
}
extension InoutParameters {
@differentiable
static func staticMethod(_ lhs: inout Self, rhs: Self) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable
static func multipleSemanticResults(_ lhs: inout Self, rhs: Self) -> Self {}
}
extension InoutParameters {
@differentiable
mutating func mutatingMethod(_ other: Self) {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@differentiable
mutating func mutatingMethod(_ other: Self) -> Self {}
}
// Test accessors: `set`, `_read`, `_modify`.
struct Accessors: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
var stored: Float
var computed: Float {
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable
set { stored = newValue }
// `_read` is a coroutine: `(Self) -> () -> ()`.
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable
_read { yield stored }
// `_modify` is a coroutine: `(inout Self) -> () -> ()`.
// expected-error @+1 {{'@differentiable' attribute cannot be applied to this declaration}}
@differentiable
_modify { yield &stored }
}
}
// expected-error @+1 {{cannot differentiate functions returning opaque result types}}
@differentiable
func opaqueResult(_ x: Float) -> some Differentiable { x }
| apache-2.0 | 337970b77c87b4285a155517e2452201 | 31.094444 | 185 | 0.696382 | 4.055458 | false | false | false | false |
carabina/SIFloatingCollection_Swift | Example/Example/BubblesScene.swift | 10 | 4009 | //
// BubblesScene.swift
// Example
//
// Created by Neverland on 15.08.15.
// Copyright (c) 2015 ProudOfZiggy. All rights reserved.
//
import SpriteKit
extension CGFloat {
public static func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
public static func random(#min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat.random() * (max - min) + min
}
}
class BubblesScene: SIFloatingCollectionScene {
var bottomOffset: CGFloat = 200
var topOffset: CGFloat = 0
override func didMoveToView(view: SKView) {
super.didMoveToView(view)
configure()
}
private func configure() {
backgroundColor = SKColor.whiteColor()
scaleMode = .AspectFill
allowMultipleSelection = false
var bodyFrame = frame
bodyFrame.size.width = CGFloat(magneticField.minimumRadius)
bodyFrame.origin.x -= bodyFrame.size.width / 2
bodyFrame.size.height = frame.size.height - bottomOffset
bodyFrame.origin.y = frame.size.height - bodyFrame.size.height - topOffset
physicsBody = SKPhysicsBody(edgeLoopFromRect: bodyFrame)
magneticField.position = CGPointMake(frame.size.width / 2, frame.size.height / 2 + bottomOffset / 2 - topOffset)
}
override func addChild(node: SKNode) {
if node is BubbleNode {
var x = CGFloat.random(min: -bottomOffset, max: -node.frame.size.width)
var y = CGFloat.random(
min: frame.size.height - bottomOffset - node.frame.size.height,
max: frame.size.height - topOffset - node.frame.size.height
)
if floatingNodes.count % 2 == 0 || floatingNodes.isEmpty {
x = CGFloat.random(
min: frame.size.width + node.frame.size.width,
max: frame.size.width + bottomOffset
)
}
node.position = CGPointMake(x, y)
}
super.addChild(node)
}
func performCommitSelectionAnimation() {
physicsWorld.speed = 0
var sortedNodes = sortedFloatingNodes()
var actions: [SKAction] = []
for node in sortedNodes {
node.physicsBody = nil
let action = actionForFloatingNode(node)
actions.append(action)
}
runAction(SKAction.sequence(actions))
}
func throwNode(node: SKNode, toPoint: CGPoint, completion block: (() -> Void)!) {
node.removeAllActions()
let movingXAction = SKAction.moveToX(toPoint.x, duration: 0.2)
let movingYAction = SKAction.moveToY(toPoint.y, duration: 0.4)
let resize = SKAction.scaleTo(0.3, duration: 0.4)
let throwAction = SKAction.group([movingXAction, movingYAction, resize])
node.runAction(throwAction)
}
func sortedFloatingNodes() -> [SIFloatingNode]! {
var sortedNodes = floatingNodes.sorted { (node: SIFloatingNode, nextNode: SIFloatingNode) -> Bool in
let distance = distanceBetweenPoints(node.position, self.magneticField.position)
let nextDistance = distanceBetweenPoints(nextNode.position, self.magneticField.position)
return distance < nextDistance && node.state != .Selected
}
return sortedNodes
}
func actionForFloatingNode(node: SIFloatingNode!) -> SKAction {
let action = SKAction.runBlock({ () -> Void in
if let index = find(self.floatingNodes, node) {
self.removeFloatinNodeAtIndex(index)
if node.state == .Selected {
self.throwNode(
node,
toPoint: CGPointMake(self.size.width / 2, self.size.height + 40),
completion: {
node.removeFromParent()
}
)
}
}
})
return action
}
} | mit | 88b6c8e2cff9c2f34a63664ed2d68a46 | 35.126126 | 120 | 0.587179 | 4.661628 | false | false | false | false |
kean/Arranged | Tests/SubviewsManagementTests.swift | 1 | 3389 | // The MIT License (MIT)
//
// Copyright (c) 2018 Alexander Grebenyuk (github.com/kean).
import Arranged
import UIKit
import XCTest
class SubviewsManagementTests: XCTestCase {
func testInitialization() {
let view = UIView()
let stack = StackView(arrangedSubviews: [view])
XCTAssertEqual(stack.arrangedSubviews.count, 1)
XCTAssertTrue(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
}
func testThatArrangedViewAreAdded() {
let stack = StackView()
let view = UIView()
stack.addArrangedSubview(view)
XCTAssertEqual(stack.arrangedSubviews.count, 1)
XCTAssertTrue(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
}
func testThatArrangedViewsAreRemoved() {
let stack = StackView()
let view = UIView()
stack.addArrangedSubview(view)
XCTAssertEqual(stack.arrangedSubviews.count, 1)
XCTAssertTrue(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
stack.removeArrangedSubview(view)
XCTAssertEqual(stack.arrangedSubviews.count, 0)
XCTAssertFalse(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
view.removeFromSuperview()
XCTAssertFalse(stack.subviews.contains(view))
}
func testThatArrangedViewIsRemovedWhenItIsRemovedFromSuperview() {
let stack = StackView()
let view = UIView()
stack.addArrangedSubview(view)
XCTAssertEqual(stack.arrangedSubviews.count, 1)
XCTAssertTrue(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
view.removeFromSuperview()
XCTAssertEqual(stack.arrangedSubviews.count, 0)
XCTAssertFalse(stack.arrangedSubviews.contains(view))
XCTAssertFalse(stack.subviews.contains(view))
}
func testThatViewCanBeAddedAsSubviewWithoutBecomingManagedByStackView() {
let view = UIView()
let stack = StackView(arrangedSubviews: [view])
view.removeFromSuperview()
XCTAssertEqual(stack.arrangedSubviews.count, 0)
XCTAssertFalse(stack.arrangedSubviews.contains(view))
XCTAssertFalse(stack.subviews.contains(view))
}
func testThatItemCanBeAddedAsSubviewWithoutBecomingArranged() {
let stack = StackView()
let view = UIView()
stack.addSubview(view)
XCTAssertEqual(stack.arrangedSubviews.count, 0)
XCTAssertFalse(stack.arrangedSubviews.contains(view))
XCTAssertTrue(stack.subviews.contains(view))
}
func testThatInsertArrangedSubivewAtIndexMethodUpdatesIndexOfExistingSubview() {
let stack = StackView()
let view1 = UIView()
let view2 = UIView()
stack.addArrangedSubview(view1)
stack.addArrangedSubview(view2)
XCTAssertEqual(stack.arrangedSubviews.count, 2)
XCTAssertTrue(stack.arrangedSubviews[0] === view1)
XCTAssertTrue(stack.arrangedSubviews[1] === view2)
stack.insertArrangedSubview(view2, atIndex: 0)
XCTAssertEqual(stack.arrangedSubviews.count, 2)
XCTAssertTrue(stack.arrangedSubviews[0] === view2)
XCTAssertTrue(stack.arrangedSubviews[1] === view1)
}
}
| mit | a33b1f384d73378adc9458c22beeaccc | 36.241758 | 84 | 0.688404 | 5.050671 | false | true | false | false |
mozilla-mobile/firefox-ios | Shared/FeatureSwitch.swift | 2 | 3266 | // 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 Foundation
/// Steadily growing set of feature switches controlling access to features by populations of Release users.
open class FeatureSwitches {
}
/// Small class to allow a percentage of users to access a given feature.
/// It is deliberately low tech, and is not remotely changeable.
/// Randomized bucketing is only applied when the app's release build channel.
open class FeatureSwitch {
let featureID: String
let buildChannel: AppBuildChannel
let nonChannelValue: Bool
let percentage: Int
fileprivate let switchKey: String
init(named featureID: String, _ value: Bool = true, allowPercentage percentage: Int, buildChannel: AppBuildChannel = .release) {
self.featureID = featureID
self.percentage = percentage
self.buildChannel = buildChannel
self.nonChannelValue = value
self.switchKey = "feature_switches.\(self.featureID)"
}
/// Is this user a member of the bucket that is allowed to use this feature.
/// Bucketing is decided with the hash of a UUID, which is randomly generated and cached
/// in the preferences.
/// This gives us stable properties across restarts and new releases.
open func isMember(_ prefs: Prefs) -> Bool {
// Only use bucketing if we're in the correct build channel, and feature flag is true.
guard buildChannel == AppConstants.BuildChannel, nonChannelValue else {
return nonChannelValue
}
// Check if this feature has been enabled by the user
let key = "\(self.switchKey).enabled"
if let isEnabled = prefs.boolForKey(key) {
return isEnabled
}
return lowerCaseS(prefs) < self.percentage
}
/// Is this user always a member of the test set, whatever the percentage probability?
/// This _only_ tests the probabilities, not the other conditions.
open func alwaysMembership(_ prefs: Prefs) -> Bool {
return lowerCaseS(prefs) == 99
}
/// Reset the random component of this switch (`lowerCaseS`). This is primarily useful for testing.
open func resetMembership(_ prefs: Prefs) {
let uuidKey = "\(self.switchKey).uuid"
prefs.removeObjectForKey(uuidKey)
}
// If the set of all possible values the switch can be in is `S` (integers between 0 and 99)
// then the specific value is `s`.
// We use this to compare with the probability of membership.
fileprivate func lowerCaseS(_ prefs: Prefs) -> Int {
// Use a branch of the prefs.
let uuidKey = "\(self.switchKey).uuid"
let uuidString: String
if let string = prefs.stringForKey(uuidKey) {
uuidString = string
} else {
uuidString = UUID().uuidString
prefs.setString(uuidString, forKey: uuidKey)
}
let hash = abs(uuidString.hashValue)
return hash % 100
}
open func setMembership(_ isEnabled: Bool, for prefs: Prefs) {
let key = "\(self.switchKey).enabled"
prefs.setBool(isEnabled, forKey: key)
}
}
| mpl-2.0 | 8ca770db668eb9cf23c0c0b3f198643d | 38.349398 | 132 | 0.66932 | 4.632624 | false | false | false | false |
benlangmuir/swift | test/PrintAsObjC/getter_setter.swift | 26 | 1218 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -emit-ir -o %t/getter_setter.ir -emit-objc-header-path %t/getter_setter.h -import-objc-header %S/Inputs/propertyWithOddGetterSetterNames.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck --check-prefix="HEADER" %s < %t/getter_setter.h
// RUN: %FileCheck --check-prefix="IRCHECK1" %s < %t/getter_setter.ir
// RUN: %FileCheck --check-prefix="IRCHECK2" %s < %t/getter_setter.ir
//
// REQUIRES: objc_interop
import Foundation
// rdar://problem/55519276: Make sure we're using the right selector names as
// written in Objective-C.
public final class Saiyan: NSObject, PowerProtocol {
public var level: Int64
// HEADER: @property (nonatomic, getter=getPower, setter=setPower:) int64_t level;
// IRCHECK1: METACLASS_DATA__TtC13getter_setter6Saiyan
// IRCHECK1: selector_data(getPower)
// IRCHECK1: selector_data(setPower:)
// IRCHECK1: INSTANCE_METHODS__TtC13getter_setter6Saiyan
// IRCHECK2: METACLASS_DATA__TtC13getter_setter6Saiyan
// IRCHECK2-NOT: selector_data(level)
// IRCHECK2-NOT: selector_data(setLevel:)
// IRCHECK2: INSTANCE_METHODS__TtC13getter_setter6Saiyan
public override init() {
level = 9001
}
}
| apache-2.0 | 6cc742aff292ea9feb891388240c7e21 | 44.111111 | 218 | 0.731527 | 3.21372 | false | false | false | false |
benlangmuir/swift | SwiftCompilerSources/Sources/Optimizer/PassManager/Passes.swift | 4 | 1897 | //===--- Passes.swift ---- instruction and function passes ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SIL
import OptimizerBridging
struct FunctionPass {
let name: String
let runFunction: (Function, PassContext) -> ()
public init(name: String,
_ runFunction: @escaping (Function, PassContext) -> ()) {
self.name = name
self.runFunction = runFunction
}
func run(_ bridgedCtxt: BridgedFunctionPassCtxt) {
let function = bridgedCtxt.function.function
let context = PassContext(_bridged: bridgedCtxt.passContext)
runFunction(function, context)
}
}
struct InstructionPass<InstType: Instruction> {
let name: String
let runFunction: (InstType, PassContext) -> ()
public init(name: String,
_ runFunction: @escaping (InstType, PassContext) -> ()) {
self.name = name
self.runFunction = runFunction
}
func run(_ bridgedCtxt: BridgedInstructionPassCtxt) {
let inst = bridgedCtxt.instruction.getAs(InstType.self)
let context = PassContext(_bridged: bridgedCtxt.passContext)
runFunction(inst, context)
}
}
struct ModulePass {
let name: String
let runFunction: (ModulePassContext) -> ()
public init(name: String,
_ runFunction: @escaping (ModulePassContext) -> ()) {
self.name = name
self.runFunction = runFunction
}
func run(_ bridgedCtxt: BridgedPassContext) {
let context = ModulePassContext(_bridged: bridgedCtxt)
runFunction(context)
}
}
| apache-2.0 | 9c3c332081b1aaa1160a92ee0ce6fdf9 | 27.742424 | 80 | 0.658408 | 4.660934 | false | false | false | false |
perlguy99/GAS3_XLActionControllerAdditions | Example/Pods/XLActionController/Source/ActionControllerSettings.swift | 2 | 9717 | // ActionControllerSettings.swiftg
// XLActionController ( https://github.com/xmartlabs/XLActionController )
//
// Copyright (c) 2015 Xmartlabs ( http://xmartlabs.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 UIKit
public struct ActionControllerSettings {
/** Struct that contains properties to configure the actions controller's behavior */
public struct Behavior {
/**
* A Boolean value that determines whether the action controller must be dismissed when the user taps the
* background view. Its default value is `true`.
*/
public var hideOnTap = true
/**
* A Boolean value that determines whether the action controller must be dismissed when the user scroll down
* the collection view. Its default value is `true`.
*
* @discussion If `scrollEnabled` value is `false`, this property is discarded and the action controller won't
* be dismissed if the user scrolls down the collection view.
*/
public var hideOnScrollDown = true
/**
* A Boolean value that determines whether the collectionView's scroll is enabled. Its default value is `false`
*/
public var scrollEnabled = false
/**
* A Boolean value that controls whether the collection view scroll bounces past the edge of content and back
* again. Its default value is `false`
*/
public var bounces = false
/**
* A Boolean value that determines whether if the collection view layout will use UIDynamics to animate its
* items. Its default value is `false`
*/
public var useDynamics = false
}
/** Struct that contains properties to configure the cancel view */
public struct CancelViewStyle {
/**
* A Boolean value that determines whether cancel view is shown. Its default value is `false`. Its default
* value is `false`.
*/
public var showCancel = false
/**
* The cancel view's title. Its default value is "Cancel".
*/
public var title: String? = "Cancel"
/**
* The cancel view's height. Its default value is `60`.
*/
public var height = CGFloat(60.0)
/**
* The cancel view's background color. Its default value is `UIColor.blackColor().colorWithAlphaComponent(0.8)`.
*/
public var backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
}
/** Struct that contains properties to configure the collection view's style */
public struct CollectionViewStyle {
/**
* A float that determines the margins between the collection view and the container view's margins.
* Its default value is `0`
*/
public var lateralMargin: CGFloat = 0
/**
* A float that determines the cells' height when using UIDynamics to animate items. Its default value is `50`.
*/
public var cellHeightWhenDynamicsIsUsed: CGFloat = 50
}
/** Struct that contains properties to configure the animation when presenting the action controller */
public struct PresentAnimationStyle {
/**
* A float value that is used as damping for the animation block. Its default value is `1.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var damping = CGFloat(1.0)
/**
* A float value that is used as delay for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var delay = NSTimeInterval(0.0)
/**
* A float value that determines the animation duration. Its default value is `0.7`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var duration = NSTimeInterval(0.7)
/**
* A float value that is used as `springVelocity` for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var springVelocity = CGFloat(0.0)
/**
* A mask of options indicating how you want to perform the animations. Its default value is `UIViewAnimationOptions.CurveEaseOut`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var options = UIViewAnimationOptions.CurveEaseOut
}
/** Struct that contains properties to configure the animation when dismissing the action controller */
public struct DismissAnimationStyle {
/**
* A float value that is used as damping for the animation block. Its default value is `1.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var damping = CGFloat(1.0)
/**
* A float value that is used as delay for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var delay = NSTimeInterval(0.0)
/**
* A float value that determines the animation duration. Its default value is `0.7`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var duration = NSTimeInterval(0.7)
/**
* A float value that is used as `springVelocity` for the animation block. Its default value is `0.0`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var springVelocity = CGFloat(0.0)
/**
* A mask of options indicating how you want to perform the animations. Its default value is `UIViewAnimationOptions.CurveEaseIn`.
* @see: animateWithDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:
*/
public var options = UIViewAnimationOptions.CurveEaseIn
/**
* A float value that makes the action controller's to be animated until the bottomof the screen plus this value.
*/
public var offset = CGFloat(0)
}
/** Struct that contains all properties related to presentation & dismissal animations */
public struct AnimationStyle {
/**
* A size value that is used to scale the presenting view controller when the action controller is being
* presented. If `nil` is set, then the presenting view controller won't be scaled. Its default value is
* `(0.9, 0.9)`.
*/
public var scale: CGSize? = CGSizeMake(0.9, 0.9)
/** Stores presentation animation properties */
public var present = PresentAnimationStyle()
/** Stores dismissal animation properties */
public var dismiss = DismissAnimationStyle()
}
/** Struct that contains properties related to the status bar's appearance */
public struct StatusBarStyle {
/**
* A Boolean value that determines whether the status bar should be visible or hidden when the action controller
* is visible. Its default value is `true`.
*/
public var showStatusBar = true
/**
* A value that determines the style of the device’s status bar when the action controller is visible. Its
* default value is `UIStatusBarStyle.LightContent`.
*/
public var style = UIStatusBarStyle.LightContent
}
/** Stores the behavior's properties values */
public var behavior = Behavior()
/** Stores the cancel view's properties values */
public var cancelView = CancelViewStyle()
/** Stores the collection view's properties values */
public var collectionView = CollectionViewStyle()
/** Stores the animations' properties values */
public var animation = AnimationStyle()
/** Stores the status bar's properties values */
public var statusBar = StatusBarStyle()
/**
* Create the default settings
* @return The default value for settings
*/
public static func defaultSettings() -> ActionControllerSettings {
return ActionControllerSettings()
}
}
| mit | e22b9ba98220908ad9038344875c587d | 47.094059 | 140 | 0.669583 | 5.277023 | false | false | false | false |
johnpatrickmorgan/FireRoutes | Example/Tests/Examples.swift | 1 | 1452 | //
// ExampleRoutes.swift
// Pods
//
// Created by John Morgan on 08/12/2015.
//
//
import FireRoutes
import Alamofire
import ObjectMapper
import AlamofireObjectMapper
let baseURL = "http://www.myserver.com/api"
class StringRoute: Route<String> {
override init() {
super.init()
request = GET(baseURL + "/status")
responseSerializer = DataRequest.stringResponseSerializer()
}
}
class JSONRoute: Route<Any> {
override init() {
super.init()
request = GET(baseURL + "/example")
responseSerializer = DataRequest.jsonResponseSerializer()
}
}
class ImageRoute: Route<UIImage> {
init(userId: String) {
super.init()
request = GET(baseURL + "/avatar", parameters: ["userid" : userId])
responseSerializer = DataRequest.imageResponseSerializer()
}
}
struct MappedModel: Mappable {
var exampleURL: URL!
var exampleString: String!
var exampleInt: Int!
init?(map: Map) {
}
mutating func mapping(map: Map) {
exampleURL <- (map["Example_URL"], URLTransform())
exampleString <- (map["Example_String"])
exampleInt <- (map["Example_Int"])
}
}
class MappedModelRoute: Route<MappedModel> {
override init() {
super.init()
request = GET(baseURL + "/model")
responseSerializer = DataRequest.ObjectMapperSerializer(nil)
}
}
| mit | 13253a25f39bee709f12e5bde47dd6b5 | 20.352941 | 75 | 0.608815 | 4.295858 | false | false | false | false |
kreactive/JSONWebToken | JSONWebToken/RSASSA_PKCS1.swift | 1 | 5646 | //
// RSASSA_PKCS1.swift
// JSONWebToken
//
// Created by Antoine Palazzolo on 18/11/15.
//
import Foundation
import Security
private func paddingForHashFunction(_ f : SignatureAlgorithm.HashFunction) -> SecPadding {
switch f {
case .sha256:
return SecPadding.PKCS1SHA256
case .sha384:
return SecPadding.PKCS1SHA384
case .sha512:
return SecPadding.PKCS1SHA512
}
}
public struct RSAKey {
enum Error : Swift.Error {
case securityError(OSStatus)
case publicKeyNotFoundInCertificate
case cannotCreateCertificateFromData
case invalidP12ImportResult
case invalidP12NoIdentityFound
}
let value : SecKey
public init(secKey :SecKey) {
self.value = secKey
}
public init(secCertificate cert: SecCertificate) throws {
var trust : SecTrust? = nil
let result = SecTrustCreateWithCertificates(cert, nil, &trust)
if result == errSecSuccess && trust != nil {
if let publicKey = SecTrustCopyPublicKey(trust!) {
self.init(secKey : publicKey)
} else {
throw Error.publicKeyNotFoundInCertificate
}
} else {
throw Error.securityError(result)
}
}
//Creates a certificate object from a DER representation of a certificate.
public init(certificateData data: Data) throws {
if let cert = SecCertificateCreateWithData(nil, data as CFData) {
try self.init(secCertificate : cert)
} else {
throw Error.cannotCreateCertificateFromData
}
}
public static func keysFromPkcs12Identity(_ p12Data : Data, passphrase : String) throws -> (publicKey : RSAKey, privateKey : RSAKey) {
var importResult : CFArray? = nil
let importParam = [kSecImportExportPassphrase as String: passphrase]
let status = SecPKCS12Import(p12Data as CFData,importParam as CFDictionary, &importResult)
guard status == errSecSuccess else { throw Error.securityError(status) }
if let array = importResult.map({unsafeBitCast($0,to: NSArray.self)}),
let content = array.firstObject as? NSDictionary,
let identity = (content[kSecImportItemIdentity as String] as! SecIdentity?)
{
var privateKey : SecKey? = nil
var certificate : SecCertificate? = nil
let status = (
SecIdentityCopyPrivateKey(identity, &privateKey),
SecIdentityCopyCertificate(identity, &certificate)
)
guard status.0 == errSecSuccess else { throw Error.securityError(status.0) }
guard status.1 == errSecSuccess else { throw Error.securityError(status.1) }
if privateKey != nil && certificate != nil {
return try (RSAKey(secCertificate: certificate!),RSAKey(secKey: privateKey!))
} else {
throw Error.invalidP12ImportResult
}
} else {
throw Error.invalidP12NoIdentityFound
}
}
}
public struct RSAPKCS1Verifier : SignatureValidator {
let hashFunction : SignatureAlgorithm.HashFunction
let key : RSAKey
public init(key : RSAKey, hashFunction : SignatureAlgorithm.HashFunction) {
self.hashFunction = hashFunction
self.key = key
}
public func canVerifyWithSignatureAlgorithm(_ alg : SignatureAlgorithm) -> Bool {
if case SignatureAlgorithm.rsassa_PKCS1(self.hashFunction) = alg {
return true
}
return false
}
public func verify(_ input : Data, signature : Data) -> Bool {
let signedDataHash = input.sha(self.hashFunction)
let padding = paddingForHashFunction(self.hashFunction)
let result = signature.withUnsafeBytes { signatureRawPointer in
signedDataHash.withUnsafeBytes { signedHashRawPointer in
SecKeyRawVerify(
key.value,
padding,
signedHashRawPointer,
signedDataHash.count,
signatureRawPointer,
signature.count
)
}
}
switch result {
case errSecSuccess:
return true
default:
return false
}
}
}
public struct RSAPKCS1Signer : TokenSigner {
enum Error : Swift.Error {
case securityError(OSStatus)
}
let hashFunction : SignatureAlgorithm.HashFunction
let key : RSAKey
public init(hashFunction : SignatureAlgorithm.HashFunction, key : RSAKey) {
self.hashFunction = hashFunction
self.key = key
}
public var signatureAlgorithm : SignatureAlgorithm {
return .rsassa_PKCS1(self.hashFunction)
}
public func sign(_ input : Data) throws -> Data {
let signedDataHash = input.sha(self.hashFunction)
let padding = paddingForHashFunction(self.hashFunction)
var result = Data(count: SecKeyGetBlockSize(self.key.value))
var resultSize = result.count
let status = result.withUnsafeMutableBytes { resultBytes in
SecKeyRawSign(key.value, padding, (signedDataHash as NSData).bytes.bindMemory(to: UInt8.self, capacity: signedDataHash.count), signedDataHash.count, UnsafeMutablePointer<UInt8>(resultBytes), &resultSize)
}
switch status {
case errSecSuccess:
return result.subdata(in: 0..<resultSize)
default:
throw Error.securityError(status)
}
}
}
| mit | 10a3d0f6df0f29043b1dbee1f8e016ca | 33.426829 | 215 | 0.619908 | 5.11413 | false | false | false | false |
RicardoKoch/ShopSearch | ShopSearch/Classes/CategoriesParser.swift | 1 | 3527 | //
// CategoriesParser.swift
// ShopSearch
//
// Created by Ricardo Koch on 4/5/16.
// Copyright © 2016 Ricardo Koch. All rights reserved.
//
import UIKit
protocol CategoriesParserDelegate: HtmlParserDelegate {
func parserDidFinishCategories(_ categories:[String:GoogleCategory])
func parserDidFinishCategoriesWithError(message:String)
}
class CategoriesParser: HtmlParser {
weak var delegateInterceptor: CategoriesParserDelegate?
override var delegate: HtmlParserDelegate? {
didSet {
if let newValue = delegate as? CategoriesParserDelegate {
delegateInterceptor = newValue
}
else {
delegateInterceptor = nil
}
}
}
func parseCategories(onData data:Data) -> [String:GoogleCategory]? {
let str = String(data: data, encoding: String.Encoding.ascii) ?? ""
var categories = [String:GoogleCategory]()
var addedStack = [GoogleCategory]()
let topParentCat = GoogleCategory(withId: "-1", name: "TOP")
categories["-1"] = topParentCat
let allCategories = str.components(separatedBy: "\n")
let size = allCategories.count
for i in 1 ..< size {
let category = allCategories[i]
let parts = category.components(separatedBy: " - ")
if parts.count == 2 {
let id = parts[0]
let fullName = parts[1]
let cat:GoogleCategory
if fullName.range(of: " > ") != nil {
//This is a sub category.
let catNames = fullName.components(separatedBy: " > ")
let catName = catNames.last ?? ""
let parentName = catNames[catNames.count-2]
while addedStack.last?.name != parentName && addedStack.count > 0 {
addedStack.removeLast()
}
cat = GoogleCategory(withId: id, name: catName)
cat.parent = addedStack.last
addedStack.last?.children.append(cat)
}
else {
cat = GoogleCategory(withId: id, name: fullName)
topParentCat.children.append(cat) //Add child of top category to make fetch faster later
}
categories[id] = cat
addedStack.append(cat)
}
}
let defaults = UserDefaults.standard
let encodedCategories = NSKeyedArchiver.archivedData(withRootObject: categories)
defaults.set(encodedCategories, forKey: CategoriesArchiveKey)
return categories
}
}
extension CategoriesParser: GoogleNetworkRequestDelegate {
func googleRequestDidComplete(_ results:Data?) {
let cat: [String:GoogleCategory]?
if results != nil {
cat = self.parseCategories(onData: results!)
}
else {
cat = nil
}
if cat != nil {
self.delegateInterceptor?.parserDidFinishCategories(cat!)
}
else {
self.delegateInterceptor?.parserDidFinishCategoriesWithError(message: "No data parsed from source")
}
}
func googleRequestDidFail() {
self.delegateInterceptor?.parserDidFinishCategoriesWithError(message: "Fail to parse data from source")
}
}
| mit | 946a4c4e0b5a9bd0df0770b4a17a7b8a | 30.765766 | 111 | 0.558423 | 5.350531 | false | false | false | false |
einsteinx2/iSub | Classes/AudioEngine/Bass Wrapper/Bass.swift | 1 | 14506 | //
// Bass.swift
// iSub Beta
//
// Created by Benjamin Baron on 9/17/17.
// Copyright © 2017 Ben Baron. All rights reserved.
//
import Foundation
struct Bass {
static func printChannelInfo(_ channel: HSTREAM) {
var i = BASS_CHANNELINFO()
BASS_ChannelGetInfo(channel, &i)
let bytes = BASS_ChannelGetLength(channel, UInt32(BASS_POS_BYTE))
let time = BASS_ChannelBytes2Seconds(channel, bytes)
log.debug("channel type = \(i.ctype) (\(self.formatForChannel(channel)))\nlength = \(bytes) (seconds: \(time) flags: \(i.flags) freq: \(i.freq) origres: \(i.origres)")
}
static func formatForChannel(_ channel: HSTREAM) -> String {
var i = BASS_CHANNELINFO()
BASS_ChannelGetInfo(channel, &i)
/*if (plugin)
{
// using a plugin
const BASS_PLUGININFO *pinfo=BASS_PluginGetInfo(plugin) // get plugin info
int a
for (a=0a<pinfo->formatca++)
{
if (pinfo->formats[a].ctype==ctype) // found a "ctype" match...
return [NSString stringWithFormat:"%s", pinfo->formats[a].name] // return it's name
}
}*/
switch Int32(i.ctype) {
case BASS_CTYPE_STREAM_WV: return "WV"
case BASS_CTYPE_STREAM_MPC: return "MPC"
case BASS_CTYPE_STREAM_APE: return "APE"
case BASS_CTYPE_STREAM_FLAC: return "FLAC"
case BASS_CTYPE_STREAM_FLAC_OGG: return "FLAC"
case BASS_CTYPE_STREAM_OGG: return "OGG"
case BASS_CTYPE_STREAM_MP1: return "MP1"
case BASS_CTYPE_STREAM_MP2: return "MP2"
case BASS_CTYPE_STREAM_MP3: return "MP3"
case BASS_CTYPE_STREAM_AIFF: return "AIFF"
case BASS_CTYPE_STREAM_OPUS: return "Opus"
case BASS_CTYPE_STREAM_WAV_PCM: return "PCM WAV"
case BASS_CTYPE_STREAM_WAV_FLOAT: return "Float WAV"
// Check if WAV case works
case BASS_CTYPE_STREAM_WAV: return "WAV"
case BASS_CTYPE_STREAM_CA:
// CoreAudio codec
guard let tags = BASS_ChannelGetTags(channel, UInt32(BASS_TAG_CA_CODEC)) else {
return ""
}
return tags.withMemoryRebound(to: TAG_CA_CODEC.self, capacity: 1) { pointer in
let codec: TAG_CA_CODEC = pointer.pointee
switch codec.atype {
case kAudioFormatLinearPCM: return "LPCM"
case kAudioFormatAC3: return "AC3"
case kAudioFormat60958AC3: return "AC3"
case kAudioFormatAppleIMA4: return "IMA4"
case kAudioFormatMPEG4AAC: return "AAC"
case kAudioFormatMPEG4CELP: return "CELP"
case kAudioFormatMPEG4HVXC: return "HVXC"
case kAudioFormatMPEG4TwinVQ: return "TwinVQ"
case kAudioFormatMACE3: return "MACE 3:1"
case kAudioFormatMACE6: return "MACE 6:1"
case kAudioFormatULaw: return "μLaw 2:1"
case kAudioFormatALaw: return "aLaw 2:1"
case kAudioFormatQDesign: return "QDMC"
case kAudioFormatQDesign2: return "QDM2"
case kAudioFormatQUALCOMM: return "QCPV"
case kAudioFormatMPEGLayer1: return "MP1"
case kAudioFormatMPEGLayer2: return "MP2"
case kAudioFormatMPEGLayer3: return "MP3"
case kAudioFormatTimeCode: return "TIME"
case kAudioFormatMIDIStream: return "MIDI"
case kAudioFormatParameterValueStream: return "APVS"
case kAudioFormatAppleLossless: return "ALAC"
case kAudioFormatMPEG4AAC_HE: return "AAC-HE"
case kAudioFormatMPEG4AAC_LD: return "AAC-LD"
case kAudioFormatMPEG4AAC_ELD: return "AAC-ELD"
case kAudioFormatMPEG4AAC_ELD_SBR: return "AAC-SBR"
case kAudioFormatMPEG4AAC_HE_V2: return "AAC-HEv2"
case kAudioFormatMPEG4AAC_Spatial: return "AAC-S"
case kAudioFormatAMR: return "AMR"
case kAudioFormatAudible: return "AUDB"
case kAudioFormatiLBC: return "iLBC"
case kAudioFormatDVIIntelIMA: return "ADPCM"
case kAudioFormatMicrosoftGSM: return "GSM"
case kAudioFormatAES3: return "AES3"
default: return ""
}
}
default: return ""
}
}
static func estimateBitRate(bassStream: BassStream) -> Int {
// Default to the player bitRate
let startFilePosition: UInt64 = 0
let currentFilePosition = BASS_StreamGetFilePosition(bassStream.stream, UInt32(BASS_FILEPOS_CURRENT))
let filePosition = currentFilePosition - startFilePosition
let decodedPosition = BASS_ChannelGetPosition(bassStream.stream, UInt32(BASS_POS_BYTE|BASS_POS_DECODE)) // decoded PCM position
let decodedSeconds = BASS_ChannelBytes2Seconds(bassStream.stream, decodedPosition)
guard decodedPosition > 0 && decodedSeconds > 0 else {
return bassStream.song.estimatedBitRate
}
let bitRateFloat = (Float(filePosition) * 8.0) / Float(decodedSeconds)
guard bitRateFloat < Float(Int.max) && bitRateFloat > Float(Int.min) else {
return bassStream.song.estimatedBitRate
}
var bitRate = Int(bitRateFloat / 1000.0)
bitRate = bitRate > 1000000 ? 1 : bitRate
var i = BASS_CHANNELINFO()
BASS_ChannelGetInfo(bassStream.stream, &i)
// Check the current stream format, and make sure that the bitRate is in the correct range
// otherwise use the song's estimated bitRate instead (to keep something like a 10000 kbitRate on an mp3 from being used for buffering)
switch Int32(i.ctype) {
case BASS_CTYPE_STREAM_WAV_PCM,
BASS_CTYPE_STREAM_WAV_FLOAT,
BASS_CTYPE_STREAM_WAV,
BASS_CTYPE_STREAM_AIFF,
BASS_CTYPE_STREAM_WV,
BASS_CTYPE_STREAM_FLAC,
BASS_CTYPE_STREAM_FLAC_OGG:
if bitRate < 330 || bitRate > 12000 {
bitRate = bassStream.song.estimatedBitRate
}
case BASS_CTYPE_STREAM_OGG,
BASS_CTYPE_STREAM_MP1,
BASS_CTYPE_STREAM_MP2,
BASS_CTYPE_STREAM_MP3,
BASS_CTYPE_STREAM_MPC:
if bitRate > 450 {
bitRate = bassStream.song.estimatedBitRate
}
case BASS_CTYPE_STREAM_CA:
// CoreAudio codec
guard let tags = BASS_ChannelGetTags(bassStream.stream, UInt32(BASS_TAG_CA_CODEC)) else {
bitRate = bassStream.song.estimatedBitRate
break
}
tags.withMemoryRebound(to: TAG_CA_CODEC.self, capacity: 1) { pointer in
let codec: TAG_CA_CODEC = pointer.pointee
switch codec.atype {
case kAudioFormatLinearPCM,
kAudioFormatAppleLossless:
if bitRate < 330 || bitRate > 12000 {
bitRate = bassStream.song.estimatedBitRate
}
case kAudioFormatMPEG4AAC,
kAudioFormatMPEG4AAC_HE,
kAudioFormatMPEG4AAC_LD,
kAudioFormatMPEG4AAC_ELD,
kAudioFormatMPEG4AAC_ELD_SBR,
kAudioFormatMPEG4AAC_HE_V2,
kAudioFormatMPEG4AAC_Spatial,
kAudioFormatMPEGLayer1,
kAudioFormatMPEGLayer2,
kAudioFormatMPEGLayer3:
if bitRate > 450 {
bitRate = bassStream.song.estimatedBitRate;
}
default:
// If we can't detect the format, use the estimated bitRate instead of player to be safe
bitRate = bassStream.song.estimatedBitRate
}
}
default:
// If we can't detect the format, use the estimated bitRate instead of player to be safe
bitRate = bassStream.song.estimatedBitRate
}
return bitRate
}
static func string(fromErrorCode errorCode: Int32) -> String {
switch errorCode {
case BASS_OK: return "No error! All OK"
case BASS_ERROR_MEM: return "Memory error"
case BASS_ERROR_FILEOPEN: return "Can't open the file"
case BASS_ERROR_DRIVER: return "Can't find a free/valid driver"
case BASS_ERROR_BUFLOST: return "The sample buffer was lost"
case BASS_ERROR_HANDLE: return "Invalid handle"
case BASS_ERROR_FORMAT: return "Unsupported sample format"
case BASS_ERROR_POSITION: return "Invalid position"
case BASS_ERROR_INIT: return "BASS_Init has not been successfully called"
case BASS_ERROR_START: return "BASS_Start has not been successfully called"
case BASS_ERROR_ALREADY: return "Already initialized/paused/whatever"
case BASS_ERROR_NOCHAN: return "Can't get a free channel"
case BASS_ERROR_ILLTYPE: return "An illegal type was specified"
case BASS_ERROR_ILLPARAM: return "An illegal parameter was specified"
case BASS_ERROR_NO3D: return "No 3D support"
case BASS_ERROR_NOEAX: return "No EAX support"
case BASS_ERROR_DEVICE: return "Illegal device number"
case BASS_ERROR_NOPLAY: return "Not playing"
case BASS_ERROR_FREQ: return "Illegal sample rate"
case BASS_ERROR_NOTFILE: return "The stream is not a file stream"
case BASS_ERROR_NOHW: return "No hardware voices available"
case BASS_ERROR_EMPTY: return "The MOD music has no sequence data"
case BASS_ERROR_NONET: return "No internet connection could be opened"
case BASS_ERROR_CREATE: return "Couldn't create the file"
case BASS_ERROR_NOFX: return "Effects are not available"
case BASS_ERROR_NOTAVAIL: return "Requested data is not available"
case BASS_ERROR_DECODE: return "The channel is a 'decoding channel'"
case BASS_ERROR_DX: return "A sufficient DirectX version is not installed"
case BASS_ERROR_TIMEOUT: return "Connection timedout"
case BASS_ERROR_FILEFORM: return "Unsupported file format"
case BASS_ERROR_SPEAKER: return "Unavailable speaker"
case BASS_ERROR_VERSION: return "Invalid BASS version (used by add-ons)"
case BASS_ERROR_CODEC: return "Codec is not available/supported"
case BASS_ERROR_ENDED: return "The channel/file has ended"
case BASS_ERROR_BUSY: return "The device is busy"
default: return "Unknown error."
}
}
static func printBassError(file: String = #file, line: Int = #line, function: String = #function) {
let errorCode = BASS_ErrorGetCode()
printError("BASS error: \(errorCode) - \(string(fromErrorCode: errorCode))", file: file, line: line, function: function)
}
static func testStream(forSong song: Song) -> Bool {
guard song.fileExists else {
return false
}
BASS_SetDevice(0)
var fileStream: HSTREAM = 0
song.currentPath.withCString { unsafePointer in
fileStream = BASS_StreamCreateFile(false, unsafePointer, 0, UInt64(song.size), UInt32(BASS_STREAM_DECODE|BASS_SAMPLE_FLOAT))
if fileStream == 0 {
fileStream = BASS_StreamCreateFile(false, unsafePointer, 0, UInt64(song.size), UInt32(BASS_STREAM_DECODE|BASS_SAMPLE_SOFTWARE|BASS_SAMPLE_FLOAT))
}
}
if fileStream > 0 {
BASS_StreamFree(fileStream)
return true
}
return false
}
static func bytesToBuffer(forKiloBitRate rate: Int, speedInBytesPerSec: Int) -> Int64 {
// If start date is nil somehow, or total bytes transferred is 0 somehow, return the default of 10 seconds worth of audio
if rate == 0 || speedInBytesPerSec == 0 {
return BytesForSecondsAtBitRate(seconds: 10, bitRate: rate)
}
// Get the download speed in KB/sec
let kiloBytesPerSec = Double(speedInBytesPerSec) / 1024.0
// Find out out many bytes equals 1 second of audio
let bytesForOneSecond = Double(BytesForSecondsAtBitRate(seconds: 1, bitRate: rate))
let kiloBytesForOneSecond = bytesForOneSecond / 1024.0
// Calculate the amount of seconds to start as a factor of how many seconds of audio are being downloaded per second
let secondsPerSecondFactor = kiloBytesPerSec / kiloBytesForOneSecond
var numberOfSecondsToBuffer: Double
if secondsPerSecondFactor < 0.5 {
// Downloading very slow, buffer for a while
numberOfSecondsToBuffer = 20
} else if secondsPerSecondFactor >= 0.5 && secondsPerSecondFactor < 0.7 {
// Downloading faster, but not much faster, allow for a long buffer period
numberOfSecondsToBuffer = 12
} else if secondsPerSecondFactor >= 0.7 && secondsPerSecondFactor < 0.9 {
// Downloading not much slower than real time, use a smaller buffer period
numberOfSecondsToBuffer = 8
} else if secondsPerSecondFactor >= 0.9 && secondsPerSecondFactor < 1.0 {
// Almost downloading full speed, just buffer for a short time
numberOfSecondsToBuffer = 5
} else {
// We're downloading over the speed needed, so probably the connection loss was temporary? Just buffer for a very short time
numberOfSecondsToBuffer = 2
}
// Convert from seconds to bytes
let numberOfBytesToBuffer = numberOfSecondsToBuffer * bytesForOneSecond
return Int64(numberOfBytesToBuffer)
}
}
| gpl-3.0 | e8b3b829976c86d104ae1ecb7696d62d | 48.671233 | 178 | 0.588665 | 4.6517 | false | false | false | false |
anilkumarbp/ringcentral-swift-NEW | ringcentral-swift-develop-anilkumarbp/lib/http/Headers.swift | 2 | 1979 | import Foundation
class Headers {
var contentType = "Content-Type"
var jsonContentType = "application/json"
var multipartContentType = "multipart/mixed"
var urlencodedContentType = "application/x-www-form-urlencoded"
var utf8ContentType = "charset=UTF-8"
var headers: [String: String] = [String:String]()
init() {
headers["Content-Type"] = urlencodedContentType
headers["Accept"] = jsonContentType
}
init(options: [NSObject: AnyObject]) {
for key in (options as! [String: String]).keys {
headers[key] = options[key] as? String
}
}
func getHeader(name: String) -> String! {
if hasHeader(name) {
return headers[name]
} else {
return ""
}
}
func getHeaders() -> [String: String]! {
return headers
}
func hasHeader(name: String) -> Bool {
if let x = headers[name] {
return true
} else {
return false
}
}
func setHeader(name: String!, value: String!) {
headers[name] = value
}
func setHeaders(headers: [String: String]) {
for name in headers.keys {
setHeader(name, value: headers[name])
}
}
func isContentType(type: String) -> Bool {
for value in getContentType().componentsSeparatedByString(";") {
if value == type {
return true
}
}
return false
}
func getContentType() -> String! {
if let x = headers["Content-Type"] {
return x
} else {
return ""
}
}
func isMultipart() -> Bool {
return isContentType(multipartContentType)
}
func isUrlEncoded() -> Bool {
return isContentType(urlencodedContentType)
}
func isJson() -> Bool {
return isContentType(jsonContentType)
}
} | mit | 7c05ad28f655b5604b0b1b1dba16e508 | 22.855422 | 72 | 0.533098 | 4.613054 | false | false | false | false |
sonsongithub/numsw | Playgrounds/RendererUtil.swift | 1 | 3292 | //
// RendererUtil.swift
// sandbox
//
// Created by omochimetaru on 2017/03/04.
// Copyright © 2017年 sonson. All rights reserved.
//
import CoreGraphics
// Ideally, I can just define top level function.
// But in playgroundbook, we can not use packagename so need `struct` namespacing.
public struct RendererUtil {
public static func toRadian(_ x: CGFloat) -> CGFloat {
return x * CGFloat.pi / CGFloat(180.0)
}
public static func toDegree(_ x: CGFloat) -> CGFloat {
return x * CGFloat(180.0) / CGFloat.pi
}
public static func computeBounds(points: [CGPoint]) -> CGRect {
let xs = points.map { $0.x }
let ys = points.map { $0.y }
let x0 = xs.min()!
let x1 = xs.max()!
let y0 = ys.min()!
let y1 = ys.max()!
return CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0)
}
public static func adjustViewport(viewport: CGRect) -> CGRect {
// min size constraint
var width = max(viewport.width, 2)
var height = max(viewport.height, 2)
// 10% margin
width += width * 0.1
height += height * 0.1
return CGRect(x: viewport.midX - width / 2.0,
y: viewport.midY - height / 2.0,
width: width,
height: height)
}
public static func computeViewportTransform(
from: CGRect,
to: CGRect,
flipY: Bool) -> CGAffineTransform {
let fw = from.width
let fh = from.height
let tw = to.width
let th = to.height
var trans = CGAffineTransform.identity
trans = trans.translatedBy(x: to.origin.x, y: to.origin.y)
trans = trans.translatedBy(x: (tw / 2.0), y: (th / 2.0))
let sx = tw / fw
var sy = th / fh
if flipY {
sy *= -1
}
trans = trans.scaledBy(x: sx, y: sy)
trans = trans.translatedBy(x: -(fw / 2.0), y: -(fh / 2.0))
trans = trans.translatedBy(x: -from.origin.x, y: -from.origin.y)
return trans
}
public static func computeViewportTransform(
viewport: CGRect, windowSize: CGSize) -> CGAffineTransform {
return computeViewportTransform(from: viewport,
to: CGRect(origin: CGPoint.zero,
size: windowSize),
flipY: true)
}
public static func computeTickValues(
min: CGFloat,
max: CGFloat,
step: CGFloat) -> [CGFloat] {
let x0 = Int(floor(min / step))
let x1 = Int(ceil(max / step))
var ret: [CGFloat] = []
for xi in x0...x1 {
let x = CGFloat(xi) * step
ret.append(x)
}
return ret
}
public static func drawLine(context: CGContext, points: [CGPoint]) {
context.setLineWidth(2.0)
if points.count < 2 {
return
}
context.move(to: points[0])
for i in 1..<points.count {
context.addLine(to: points[i])
}
context.strokePath()
}
}
| mit | e682ed5ae604611cb263eeed7d51df38 | 26.872881 | 83 | 0.503801 | 4.09589 | false | false | false | false |
GetZero/Give-Me-One | MyOne/个人/Controller/SettingViewController.swift | 1 | 3125 | //
// SettingViewController.swift
// MyOne
//
// Created by 韦曲凌 on 16/8/30.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import UIKit
class SettingViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerNib(UINib(nibName: "NightModeCell", bundle: nil), forCellReuseIdentifier: "NightModeCell")
tableView.registerNib(UINib(nibName: "OtherSettingCell", bundle: nil), forCellReuseIdentifier: "OtherSettingCell")
tableView.registerNib(UINib(nibName: "LogoutCell", bundle: nil), forCellReuseIdentifier: "LogoutCell")
tableView.rowHeight = 44
tableView.bounces = false
let footerView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeightWithoutNavAndTab - 440))
footerView.backgroundColor = UIColor.RGBColor(247, green: 247, blue: 247, alpha: 1)
tableView.tableFooterView = footerView
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 4
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 1
case 2:
return 3
case 3:
return 1
default:
return 0
}
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "浏览设置"
case 1:
return "缓存设置"
case 2:
return "更多"
case 3:
return " "
default:
return ""
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell: NightModeCell = tableView.dequeueReusableCellWithIdentifier("NightModeCell", forIndexPath: indexPath) as! NightModeCell
return cell
} else if indexPath.section == 1 {
let cell: OtherSettingCell = tableView.dequeueReusableCellWithIdentifier("OtherSettingCell", forIndexPath: indexPath) as! OtherSettingCell
cell.titleLabel.text = "清除缓存"
return cell
} else if indexPath.section == 2 {
let cell: OtherSettingCell = tableView.dequeueReusableCellWithIdentifier("OtherSettingCell", forIndexPath: indexPath) as! OtherSettingCell
let titles: [String] = ["去评分", "反馈", "用户协议"]
cell.titleLabel.text = titles[indexPath.row]
return cell
} else {
let cell: LogoutCell = tableView.dequeueReusableCellWithIdentifier("LogoutCell", forIndexPath: indexPath) as! LogoutCell
return cell
}
}
}
| apache-2.0 | 0094b043e2eed80de44bb0ba0895b598 | 33.886364 | 150 | 0.625733 | 5.194585 | false | false | false | false |
ninewine/SaturnTimer | Extension/CALayer+Helper.swift | 1 | 2810 | //
// CALayer+Helper.swift
// SaturnTimer
//
// Created by Tidy Nine on 1/27/16.
// Copyright © 2016 Tidy Nine. All rights reserved.
//
import UIKit
import pop
enum ShapeLayerStrokeAnimationType {
case start, end
var popPropertyName: String {
switch self {
case .start: return kPOPShapeLayerStrokeStart
case .end: return kPOPShapeLayerStrokeEnd
}
}
var animationKey: String {
switch self {
case .start: return "StrokeStartAnimation"
case .end: return "StrokeEndAnimation"
}
}
}
extension CALayer {
func st_applyAnimation(_ animation: CABasicAnimation) {
let copy = animation.copy() as! CABasicAnimation
if copy.fromValue != nil {
if let pLayer = self.presentation(){
if let kp = copy.keyPath {
copy.fromValue = pLayer.value(forKeyPath: kp)
}
}
}
if let kp = copy.keyPath {
self.add(copy, forKey: kp)
self.setValue(copy.toValue, forKeyPath:kp)
}
}
func pathStokeAnimationFrom(_ from: CGFloat?, to: CGFloat, duration: CFTimeInterval, type: ShapeLayerStrokeAnimationType, timingFunctionName: String = kCAMediaTimingFunctionDefault, completion: (()->Void)? = nil) {
applyPopAnimation(from, to: to, duration: duration, propertyName: type.popPropertyName, timingFunctionName: timingFunctionName, completion: completion)
}
func opacityAnimation(_ from: CGFloat?, to: CGFloat, duration: CFTimeInterval, timingFunctionName: String = kCAMediaTimingFunctionDefault, completion: (()->Void)? = nil) {
applyPopAnimation(from, to: to, duration: duration, propertyName: kPOPLayerOpacity, timingFunctionName: timingFunctionName, completion: completion)
}
func rotateAnimation(_ from: CGFloat?, to: CGFloat, duration: CFTimeInterval, timingFunctionName: String = kCAMediaTimingFunctionDefault, completion: (()->Void)? = nil) {
applyPopAnimation(from, to: to, duration: duration, propertyName: kPOPLayerRotation, timingFunctionName: timingFunctionName, completion: completion)
}
func applyPopAnimation (_ from: CGFloat?, to: CGFloat, duration: CFTimeInterval, propertyName: String, timingFunctionName: String = kCAMediaTimingFunctionDefault, completion: (()->Void)? = nil) {
let anim = POPBasicAnimation(propertyNamed: propertyName)
if from != nil {
anim?.fromValue = from!
}
anim?.toValue = to
anim?.duration = duration
anim?.completionBlock = { (anim, finished) in
guard let block = completion else {
return
}
block()
}
anim?.timingFunction = CAMediaTimingFunction(name: timingFunctionName)
self.pop_add(anim, forKey: propertyName)
}
func setValueWithoutImplicitAnimation(_ value: Any?, forKey key: String) {
CATransaction.begin()
CATransaction.setDisableActions(true)
self.setValue(value, forKeyPath: key)
CATransaction.commit()
}
}
| mit | ebbeff7177e420a6d811b30d5595d5ae | 33.256098 | 216 | 0.722321 | 4.295107 | false | false | false | false |
RubyNative/RubyKit | Kernel.swift | 2 | 3220 | //
// Kernel.swift
// SwiftRuby
//
// Created by John Holdsworth on 27/09/2015.
// Copyright © 2015 John Holdsworth. All rights reserved.
//
// $Id: //depot/SwiftRuby/Kernel.swift#17 $
//
// Repo: https://github.com/RubyNative/SwiftRuby
//
// See: http://ruby-doc.org/core-2.2.3/Kernel.html
//
import Foundation
public func U<T>(_ toUnwrap: T?, name: String? = nil, file: StaticString = #file, line: UInt = #line) -> T {
if toUnwrap == nil {
let msg = name != nil ? "Forced unwrap of \(name ?? "No name") fail" : "Forced unwrap fail"
_throw(NSException(name: NSExceptionName(rawValue: msg), reason: "\(file), \(line)", userInfo: ["msg": msg, "file": String(describing: file), "line": "\(line)"] ))
}
return toUnwrap!
}
public enum WarningDisposition {
case ignore, warn, `throw`, fatal
}
public var WARNING_DISPOSITION: WarningDisposition = .warn
public var LAST_WARNING: String?
public func SRLog(_ msg: String, file: StaticString = #file, line: UInt = #line) {
LAST_WARNING = msg+" at \(file)#\(line)"
if WARNING_DISPOSITION == .throw {
_throw(NSException(name: NSExceptionName(rawValue: msg), reason: LAST_WARNING, userInfo: ["msg": msg, "file": String(describing: file), "line": "\(line)"] ))
}
if WARNING_DISPOSITION != .ignore {
STDERR.print("SwiftRuby: \(U(LAST_WARNING))\n")
}
if WARNING_DISPOSITION == .fatal {
fatalError()
}
}
public func SRError(_ msg: String, file: StaticString, line: UInt) {
let error = String(validatingUTF8: strerror(errno )) ?? "Undecodable strerror"
SRLog(msg+": \(error)", file: file, line: line)
}
public func SRFatal(_ msg: String, file: StaticString, line: UInt) {
SRLog(msg, file: file, line: line)
fatalError()
}
public func SRNotImplemented(_ what: String, file: StaticString, line: UInt) {
SRFatal("\(what) not implemented", file: file, line: line)
}
@_silgen_name("execArgv")
func execArgv(_ executable: NSString, _ argv: NSArray)
@_silgen_name("spawnArgv")
func spawnArgv(_ executable: NSString, _ argv: NSArray) -> pid_t
open class Kernel: RubyObject {
open class func open(_ path: string_like, _ mode: string_like = "r", _ perm: Int = 0o644, file: StaticString = #file, line: UInt = #line) -> IO? {
let path = path.to_s
let index1 = path.index(path.startIndex, offsetBy: 1)
if path[path.startIndex ..< index1] == "|" {
return IO.popen(String(path[index1 ..< path.endIndex]),
mode, file: file, line: line)
}
return File.open(path, mode, perm, file: file, line: line)
}
open class func exec(_ command: string_like) {
exec("/bin/bash", ["-c", command.to_s])
}
open class func exec(_ executable: string_like, _ arguments: array_like) {
exec([executable.to_s, executable.to_s], arguments.to_a)
}
open class func exec(_ executable: array_like, _ arguments: array_like) {
execArgv(executable.to_a[0].to_s as NSString, [executable.to_a[1]]+arguments.to_a as NSArray)
}
open class func spawn(_ command: string_like) -> Int {
return Int(spawnArgv("/bin/bash", ["/bin/bash", "-c", command.to_s]))
}
}
| mit | 2f0378ae212602a1ffafbb419ebc5096 | 32.884211 | 171 | 0.625039 | 3.43177 | false | false | false | false |
vmouta/GitHubSpy | GitHubSpy/Repository.swift | 1 | 1718 | /**
* @name Repository.swift
* @partof GitHubSpy
* @description
* @author Vasco Mouta
* @created 17/12/15
*
* Copyright (c) 2015 zucred AG All rights reserved.
* This material, including documentation and any related
* computer programs, is protected by copyright controlled by
* zucred AG. All rights are reserved. Copying,
* including reproducing, storing, adapting or translating, any
* or all of this material requires the prior written consent of
* zucred AG. This material also contains confidential
* information which may not be disclosed to others without the
* prior written consent of zucred AG.
*/
import Foundation
import RealmSwift
class Repository: Object {
static let GitHubFork = "fork"
static let GitHubName = "name"
static let GitHubCreated = "created_at"
static let GitHubDescription = "description"
dynamic var name: String = ""
dynamic var desc: String = ""
dynamic var created_at: String = ""
dynamic var fork: Bool = false
var isFork: Bool {
return self.fork
}
var details: String {
var details: String = self.created_at
if !self.desc.isEmpty {
details += " - \(self.desc)"
}
return details
}
convenience init(jsonDictionary: NSDictionary) {
self.init(value: jsonDictionary)
if let description = jsonDictionary.valueForKey(Repository.GitHubDescription) as? String {
desc = description
}
}
override static func primaryKey() -> String? {
return "name"
}
override static func ignoredProperties() -> [String] {
return ["isFork", "details"]
}
} | mit | 03ff8d121f13e6e88ee6536357227f5b | 27.65 | 98 | 0.643772 | 4.405128 | false | false | false | false |
b3log/symphony-ios | HPApp/CommentsTableViewController.swift | 1 | 10292 | //
// ArticleTableViewController.swift
// HPApp
//
// Created by Meng To on 2015-01-09.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
import Spring
class CommentsTableViewController: UITableViewController, StoryTableViewCellDelegate, CommentTableViewCellDelegate, ReplyViewControllerDelegate, UISearchBarDelegate {
var story: Story!
private var searchBar : UISearchBar?
private var comments : [Comment] {
return self.story.comments.filter {
comment in
if self.keyword.length > 0 {
if comment.hasKeyword(self.keyword) {
return true
}
return false
}
return true
}
}
private var keyword : String = ""
private let transitionManager = TransitionManager()
private var loginAction: LoginAction?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = 140
tableView.rowHeight = UITableViewAutomaticDimension
// Reloading for the visible cells to layout correctly
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIApplication.sharedApplication().setStatusBarHidden(false, withAnimation: UIStatusBarAnimation.Fade)
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
coordinator.animateAlongsideTransition(nil, completion: { (context) -> Void in
self.tableView.reloadData()
})
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ReplySegue" {
let toView = segue.destinationViewController as! ReplyViewController
if let cell = sender as? CommentTableViewCell {
let indexPath = self.tableView.indexPathForCell(cell)
let comment = self.getCommentForIndexPath(indexPath!)
toView.replyable = comment
} else if let cell = sender as? StoryTableViewCell {
toView.replyable = story
}
toView.delegate = self
toView.transitioningDelegate = self.transitionManager
}
else if segue.identifier == "WebSegue" {
UIApplication.sharedApplication().setStatusBarHidden(true, withAnimation: UIStatusBarAnimation.Slide)
let webViewController = segue.destinationViewController as! WebViewController
if let url = sender as? NSURL {
webViewController.url = url
} else {
webViewController.shareTitle = story.title
webViewController.url = NSURL(string: story.url)
}
webViewController.transitioningDelegate = self.transitionManager
}
}
@IBAction func shareBarButtonPressed(sender: AnyObject) {
let shareString = story.title
let shareURL = NSURL(string: story.url)!
let activityViewController = UIActivityViewController(activityItems: [shareString, shareURL], applicationActivities: [SafariActivity(), ChromeActivity()])
activityViewController.setValue(shareString, forKey: "subject")
activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop]
presentViewController(activityViewController, animated: true, completion: nil)
}
// MARK: StoriesTableViewCellDelegate
func storyTableViewCell(cell: StoryTableViewCell, upvoteButtonPressed sender: AnyObject) {
if let token = LocalStore.accessToken() {
let indexPath = tableView.indexPathForCell(cell)!
let story = self.story
let storyId = story.id
story.upvote()
LocalStore.setStoryAsUpvoted(storyId)
configureCell(cell, atIndexPath: indexPath)
DesignerNewsService.upvoteStoryWithId(storyId, token: token) { successful in
if !successful {
story.downvote()
LocalStore.removeStoryFromUpvoted(storyId)
self.configureCell(cell, atIndexPath: indexPath)
}
}
} else {
self.loginAction = LoginAction(viewController: self, completion: nil)
}
}
func storyTableViewCell(cell: StoryTableViewCell, replyButtonPressed sender: AnyObject) {
if LocalStore.accessToken() == nil {
self.loginAction = LoginAction(viewController: self, completion: nil)
} else {
performSegueWithIdentifier("ReplySegue", sender: cell)
}
}
func storyTableViewCell(cell: StoryTableViewCell, linkDidPress link: NSURL) {
performSegueWithIdentifier("WebSegue", sender: link)
}
func storyTableViewCellSizeDidChange(cell: StoryTableViewCell) {
if let indexPath = tableView.indexPathForCell(cell) {
self.tableView.reloadData()
}
}
// MARK: CommentTableViewCellDelegate
func commentTableViewCell(cell: CommentTableViewCell, replyButtonPressed sender: AnyObject) {
if LocalStore.accessToken() == nil {
self.loginAction = LoginAction(viewController: self, completion: nil)
} else {
performSegueWithIdentifier("ReplySegue", sender: cell)
}
}
func commentTableViewCell(cell: CommentTableViewCell, upvoteButtonPressed sender: AnyObject) {
if let token = LocalStore.accessToken() {
let indexPath = tableView.indexPathForCell(cell)!
let comment = self.getCommentForIndexPath(indexPath)
let commentId = comment.id
comment.upvote()
LocalStore.setCommentAsUpvoted(commentId)
configureCell(cell, atIndexPath: indexPath)
DesignerNewsService.upvoteCommentWithId(commentId, token: token) { successful in
if !successful {
comment.downvote()
LocalStore.removeCommentFromUpvoted(commentId)
self.configureCell(cell, atIndexPath: indexPath)
}
}
} else {
self.loginAction = LoginAction(viewController: self, completion: nil)
}
}
func commentTableViewCell(cell: CommentTableViewCell, linkDidPress link: NSURL) {
performSegueWithIdentifier("WebSegue", sender: link)
}
func commentTableViewCellSizeDidChange(cell: CommentTableViewCell) {
if let indexPath = tableView.indexPathForCell(cell) {
self.tableView.reloadData()
}
}
// MARK: TableViewDelegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1 + comments.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = indexPath.row == 0 ? "StoryCell" : "CommentCell"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! UITableViewCell
// In order to make sure the cell have correct size while dequeuing,
// manually set the frame to it's parent's bounds
cell.frame = tableView.bounds
configureCell(cell, atIndexPath:indexPath)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 0 {
performSegueWithIdentifier("WebSegue", sender: self)
}
}
/*
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if searchBar == nil {
searchBar = UISearchBar(frame: CGRectMake(0, 0, tableView.frame.size.width, 44))
searchBar?.text = self.keyword
searchBar?.delegate = self
}
return searchBar
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 45;
}
*/
// MARK: Misc
func configureCell(cell:UITableViewCell, atIndexPath indexPath:NSIndexPath) {
if let storyCell = cell as? StoryTableViewCell {
let isUpvoted = LocalStore.isStoryUpvoted(story.id)
// Ignore visited state to keep the StoryCell title in black text color
storyCell.configureWithStory(story, isUpvoted: isUpvoted, isVisited: false)
storyCell.delegate = self
}
if let commentCell = cell as? CommentTableViewCell {
let comment = self.getCommentForIndexPath(indexPath)
let isUpvoted = LocalStore.isCommentUpvoted(comment.id)
commentCell.configureWithComment(comment, isUpvoted: isUpvoted)
commentCell.delegate = self
}
}
func getCommentForIndexPath(indexPath: NSIndexPath) -> Comment {
return comments[indexPath.row - 1]
}
// MARK: ReplyViewControllerDelegate
func replyViewController(controller: ReplyViewController, didReplyComment newComment: Comment, onReplyable replyable: Replyable) {
if let story = replyable as? Story {
LocalStore.setStoryAsReplied(story.id)
self.story.insertComment(newComment, atIndex: 0)
self.tableView.reloadData()
} else if let comment = replyable as? Comment {
LocalStore.setStoryAsReplied(story.id)
for (index, onComment) in enumerate(self.comments) {
if onComment == comment {
self.story.insertComment(newComment, atIndex: 0)
self.tableView.reloadData()
break
}
}
}
}
// MARK: UISearchBarDelegate
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
keyword = searchText
tableView.reloadData()
searchBar.becomeFirstResponder()
}
}
| apache-2.0 | ea525615552e8fecb7ca7cb9b49a2e0f | 35.888889 | 166 | 0.64759 | 5.639452 | false | false | false | false |
stakes/Frameless | Frameless/Helpers.swift | 2 | 4216 | //
// Helpers.swift
// Frameless
//
// Created by Jay Stakelon on 10/25/14.
// Copyright (c) 2014 Jay Stakelon. All rights reserved.
//
import Foundation
import UIKit
func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
// Adapted from obj-c solution at
// http://a2apps.com.au/lighten-or-darken-a-uicolor/
func adjustBrightness(color:UIColor, amount:CGFloat) -> UIColor {
var hue:CGFloat = 0
var saturation:CGFloat = 0
var brightness:CGFloat = 0
var alpha:CGFloat = 0
if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
brightness += (amount-1.0)
brightness = max(min(brightness, 1.0), 0.0)
return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha)
}
return color
}
// Extend UIImage with a method to create
// a UIImage from a solid color
// See: http://stackoverflow.com/questions/20300766/how-to-change-the-highlighted-color-of-a-uibutton
extension UIImage {
class func withColor(color: UIColor) -> UIImage {
let rect = CGRectMake(0, 0, 1, 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
// Grabbed from comments on
// http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/
func listAllAvailableFonts() {
for family: AnyObject in UIFont.familyNames() {
print("\(family)")
for font: AnyObject in UIFont.fontNamesForFamilyName(family as! String) {
print(" \(font)")
}
}
}
/// Given input from user, turn it into a URL, which could be either a direct URL or a search query
func urlifyUserInput(input: String) -> String {
// This method should really be tested, but I ran into trouble adding unit tests into this project due to some Cocoapods thing
let normalizedInput = input.lowercaseStringWithLocale(NSLocale.currentLocale())
// true = treat as URL, false = treat as search query
var looksLikeUrl = false
// test various cases
if normalizedInput.hasPrefix("http://") || normalizedInput.hasPrefix("https://") {
// normal prefixed urls
looksLikeUrl = true
} else if (normalizedInput.rangeOfString("\\w:\\d+", options: .RegularExpressionSearch) != nil) {
// "internal:4000"
// "192.168.1.2:4000"
looksLikeUrl = true
} else if (normalizedInput.rangeOfString("\\w\\.\\w", options: .RegularExpressionSearch) != nil) {
// "example.com"
// "192.168.1.2"
looksLikeUrl = true
}
if (looksLikeUrl) {
// This is a URL. Prefix it if needed, otherwise just pass through
let urlCandidate = input
if normalizedInput.hasPrefix("http://") || normalizedInput.hasPrefix("https://") {
return urlCandidate
} else {
return "http://" + urlCandidate
}
} else {
// This is a search query. Grab the correct URL template and drop the encoded query into it
// We are optimists here, assuming that userdefault value and search engine spec is always present,
// encoding never fails etc
let engineType = NSUserDefaults.standardUserDefaults().objectForKey(AppDefaultKeys.SearchEngine.rawValue) as! String
let engine = searchEngine(engineType)
let urlTemplate = engine!.queryURLTemplate
let encodedInput = normalizedInput.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let url = urlTemplate.stringByReplacingOccurrencesOfString("{query}", withString: encodedInput!)
return url
}
}
| mit | 4e6c49e657e582839d48d92c60d5e41a | 35.344828 | 139 | 0.658681 | 4.499466 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Modules/Messages/View/MessagesViewController.swift | 1 | 3034 | import UIKit
class MessagesViewController: UIViewController,
UITableViewDelegate,
MessagesScene {
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private weak var noMessagesPlaceholder: UIView!
let refreshIndicator = UIRefreshControl(frame: .zero)
private let dataSource = MessagesTableViewDataSource()
private lazy var logoutBarButtonItem = UIBarButtonItem(title: .logout,
style: .plain,
target: self,
action: #selector(logoutButtonTapped))
@objc private func logoutButtonTapped() {
delegate?.messagesSceneDidTapLogoutButton()
}
override func viewDidLoad() {
super.viewDidLoad()
refreshIndicator.addTarget(self, action: #selector(refreshControlValueDidChange), for: .valueChanged)
tableView.dataSource = dataSource
tableView.delegate = self
tableView.addSubview(refreshIndicator)
navigationItem.rightBarButtonItem = logoutBarButtonItem
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
delegate?.messagesSceneWillAppear()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.messagesSceneDidSelectMessage(at: indexPath)
}
var delegate: MessagesSceneDelegate?
func setMessagesTitle(_ title: String) {
super.title = title
}
func showRefreshIndicator() {
refreshIndicator.beginRefreshing()
}
func hideRefreshIndicator() {
refreshIndicator.endRefreshing()
}
func bindMessages(count: Int, with binder: MessageItemBinder) {
dataSource.binder = binder
dataSource.messageCount = count
tableView.reloadData()
}
func showMessagesList() {
tableView.isHidden = false
}
func hideMessagesList() {
tableView.isHidden = true
}
func showNoMessagesPlaceholder() {
noMessagesPlaceholder.isHidden = false
}
func hideNoMessagesPlaceholder() {
noMessagesPlaceholder.isHidden = true
}
@objc private func refreshControlValueDidChange() {
delegate?.messagesSceneDidPerformRefreshAction()
}
private class MessagesTableViewDataSource: NSObject, UITableViewDataSource {
var binder: MessageItemBinder?
var messageCount = 0
private let cellReuseIdentifier = "MessageCell"
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messageCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(MessageTableViewCell.self, for: indexPath)
binder?.bind(cell, toMessageAt: indexPath)
return cell
}
}
}
| mit | 4149703cc15eddef721a1d5c7d73bf44 | 29.959184 | 109 | 0.638431 | 6.1417 | false | false | false | false |
mkaply/firefox-ios | Shared/DateGroupedTableData.swift | 9 | 2972 | /* 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 Foundation
fileprivate func getDate(dayOffset: Int) -> Date {
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.year, .month, .day], from: Date())
let today = calendar.date(from: components)!
return calendar.date(byAdding: .day, value: dayOffset, to: today)!
}
public struct DateGroupedTableData<T: Equatable> {
let todayTimestamp = getDate(dayOffset: 0).timeIntervalSince1970
let yesterdayTimestamp = getDate(dayOffset: -1).timeIntervalSince1970
let lastWeekTimestamp = getDate(dayOffset: -7).timeIntervalSince1970
var today: [(T, TimeInterval)] = []
var yesterday: [(T, TimeInterval)] = []
var lastWeek: [(T, TimeInterval)] = []
var older: [(T, TimeInterval)] = []
public var isEmpty: Bool {
return today.isEmpty && yesterday.isEmpty && lastWeek.isEmpty && older.isEmpty
}
public init() {}
@discardableResult mutating public func add(_ item: T, timestamp: TimeInterval) -> IndexPath {
if timestamp > todayTimestamp {
today.append((item, timestamp))
return IndexPath(row: today.count - 1, section: 0)
} else if timestamp > yesterdayTimestamp {
yesterday.append((item, timestamp))
return IndexPath(row: yesterday.count - 1, section: 1)
} else if timestamp > lastWeekTimestamp {
lastWeek.append((item, timestamp))
return IndexPath(row: lastWeek.count - 1, section: 2)
} else {
older.append((item, timestamp))
return IndexPath(row: older.count - 1, section: 3)
}
}
mutating public func remove(_ item: T) {
if let index = today.firstIndex(where: { item == $0.0 }) {
today.remove(at: index)
} else if let index = yesterday.firstIndex(where: { item == $0.0 }) {
yesterday.remove(at: index)
} else if let index = lastWeek.firstIndex(where: { item == $0.0 }) {
lastWeek.remove(at: index)
} else if let index = older.firstIndex(where: { item == $0.0 }) {
older.remove(at: index)
}
}
public func numberOfItemsForSection(_ section: Int) -> Int {
switch section {
case 0:
return today.count
case 1:
return yesterday.count
case 2:
return lastWeek.count
default:
return older.count
}
}
public func itemsForSection(_ section: Int) -> [T] {
switch section {
case 0:
return today.map({ $0.0 })
case 1:
return yesterday.map({ $0.0 })
case 2:
return lastWeek.map({ $0.0 })
default:
return older.map({ $0.0 })
}
}
}
| mpl-2.0 | 26598886bab7828edb0d5fd59bc7d20b | 34.807229 | 98 | 0.592867 | 4.263989 | false | false | false | false |
abunur/HamburgerButton | HamburgerButton/HamburgerButton.swift | 1 | 6808 | //
// HamburgerButton.swift
// HamburgerButton
//
// Created by Arkadiusz on 14-07-14.
// Copyright (c) 2014 Arkadiusz Holko. All rights reserved.
//
import CoreGraphics
import QuartzCore
import UIKit
public class HamburgerButton: UIButton {
public var color: UIColor = UIColor.whiteColor() {
didSet {
for shapeLayer in shapeLayers {
shapeLayer.strokeColor = color.CGColor
}
}
}
private let top: CAShapeLayer = CAShapeLayer()
private let middle: CAShapeLayer = CAShapeLayer()
private let bottom: CAShapeLayer = CAShapeLayer()
private let width: CGFloat = 18
private let height: CGFloat = 16
private let topYPosition: CGFloat = 2
private let middleYPosition: CGFloat = 7
private let bottomYPosition: CGFloat = 12
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
let path = UIBezierPath()
path.moveToPoint(CGPoint(x: 0, y: 0))
path.addLineToPoint(CGPoint(x: width, y: 0))
for shapeLayer in shapeLayers {
shapeLayer.path = path.CGPath
shapeLayer.lineWidth = 2
shapeLayer.strokeColor = color.CGColor
// Disables implicit animations.
shapeLayer.actions = [
"transform": NSNull(),
"position": NSNull()
]
let strokingPath = CGPathCreateCopyByStrokingPath(shapeLayer.path, nil, shapeLayer.lineWidth, kCGLineCapButt, kCGLineJoinMiter, shapeLayer.miterLimit)
// Otherwise bounds will be equal to CGRectZero.
shapeLayer.bounds = CGPathGetPathBoundingBox(strokingPath)
layer.addSublayer(shapeLayer)
}
let widthMiddle = width / 2
top.position = CGPoint(x: widthMiddle, y: topYPosition)
middle.position = CGPoint(x: widthMiddle, y: middleYPosition)
bottom.position = CGPoint(x: widthMiddle, y: bottomYPosition)
}
override public func intrinsicContentSize() -> CGSize {
return CGSize(width: width, height: height)
}
public var showsMenu: Bool = true {
didSet {
// There's many animations so it's easier to set up duration and timing function at once.
CATransaction.begin()
CATransaction.setAnimationDuration(0.4)
CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(controlPoints: 0.4, 0.0, 0.2, 1.0))
let strokeStartNewValue: CGFloat = showsMenu ? 0.0 : 0.3
let positionPathControlPointY = bottomYPosition / 2
let verticalOffsetInRotatedState: CGFloat = 0.75
let topRotation = CAKeyframeAnimation(keyPath: "transform")
topRotation.values = rotationValuesFromTransform(top.transform,
endValue: showsMenu ? CGFloat(-M_PI - M_PI_4) : CGFloat(M_PI + M_PI_4))
// Kind of a workaround. Used because it was hard to animate positions of segments' such that their ends form the arrow's tip and don't cross each other.
topRotation.calculationMode = kCAAnimationCubic
topRotation.keyTimes = [0.0, 0.33, 0.73, 1.0]
top.ahk_applyKeyframeValuesAnimation(topRotation)
let topPosition = CAKeyframeAnimation(keyPath: "position")
let topPositionEndPoint = CGPoint(x: width / 2, y: showsMenu ? topYPosition : bottomYPosition + verticalOffsetInRotatedState)
topPosition.path = quadBezierCurveFromPoint(top.position,
toPoint: topPositionEndPoint,
controlPoint: CGPoint(x: width, y: positionPathControlPointY)).CGPath
top.ahk_applyKeyframePathAnimation(topPosition, endValue: NSValue(CGPoint: topPositionEndPoint))
top.strokeStart = strokeStartNewValue
let middleRotation = CAKeyframeAnimation(keyPath: "transform")
middleRotation.values = rotationValuesFromTransform(middle.transform,
endValue: showsMenu ? CGFloat(-M_PI) : CGFloat(M_PI))
middle.ahk_applyKeyframeValuesAnimation(middleRotation)
middle.strokeEnd = showsMenu ? 1.0 : 0.85
let bottomRotation = CAKeyframeAnimation(keyPath: "transform")
bottomRotation.values = rotationValuesFromTransform(bottom.transform,
endValue: showsMenu ? CGFloat(-M_PI_2 - M_PI_4) : CGFloat(M_PI_2 + M_PI_4))
bottomRotation.calculationMode = kCAAnimationCubic
bottomRotation.keyTimes = [0.0, 0.33, 0.63, 1.0]
bottom.ahk_applyKeyframeValuesAnimation(bottomRotation)
let bottomPosition = CAKeyframeAnimation(keyPath: "position")
let bottomPositionEndPoint = CGPoint(x: width / 2, y: showsMenu ? bottomYPosition : topYPosition - verticalOffsetInRotatedState)
bottomPosition.path = quadBezierCurveFromPoint(bottom.position,
toPoint: bottomPositionEndPoint,
controlPoint: CGPoint(x: 0, y: positionPathControlPointY)).CGPath
bottom.ahk_applyKeyframePathAnimation(bottomPosition, endValue: NSValue(CGPoint: bottomPositionEndPoint))
bottom.strokeStart = strokeStartNewValue
CATransaction.commit()
}
}
private var shapeLayers: [CAShapeLayer] {
return [top, middle, bottom]
}
}
extension CALayer {
func ahk_applyKeyframeValuesAnimation(animation: CAKeyframeAnimation) {
let copy = animation.copy() as! CAKeyframeAnimation
assert(!copy.values.isEmpty)
self.addAnimation(copy, forKey: copy.keyPath)
self.setValue(copy.values[copy.values.count - 1], forKeyPath:copy.keyPath)
}
// Mark: TODO: endValue could be removed from the definition, because it's possible to get it from the path (see: CGPathApply).
func ahk_applyKeyframePathAnimation(animation: CAKeyframeAnimation, endValue: NSValue) {
let copy = animation.copy() as! CAKeyframeAnimation
self.addAnimation(copy, forKey: copy.keyPath)
self.setValue(endValue, forKeyPath:copy.keyPath)
}
}
func rotationValuesFromTransform(transform: CATransform3D, #endValue: CGFloat) -> [NSValue] {
let frames = 4
// values at 0, 1/3, 2/3 and 1
return (0..<frames).map { num in
NSValue(CATransform3D: CATransform3DRotate(transform, endValue / CGFloat(frames - 1) * CGFloat(num), 0, 0, 1))
}
}
func quadBezierCurveFromPoint(startPoint: CGPoint, #toPoint: CGPoint, #controlPoint: CGPoint) -> UIBezierPath {
let quadPath = UIBezierPath()
quadPath.moveToPoint(startPoint)
quadPath.addQuadCurveToPoint(toPoint, controlPoint: controlPoint)
return quadPath
} | mit | e6707fdec9c482065b3e40b8252d499c | 38.587209 | 165 | 0.667891 | 4.787623 | false | false | false | false |
KaushalElsewhere/AllHandsOn | TryMadhu/TryMadhu/SettingsCell.swift | 1 | 866 | //
// SettingsCell.swift
// TryMadhu
//
// Created by Kaushal Elsewhere on 15/05/2017.
// Copyright © 2017 Elsewhere. All rights reserved.
//
import UIKit
class SettingsCell: TableCell {
lazy var usernameTextFild: UITextField = {
let textField = UITextField()
textField.placeholder = "Username"
textField.textColor = .darkGrayColor()
return textField
}()
override func setupViews() {
contentView.addSubview(usernameTextFild)
setupConstraints()
}
func setupConstraints() {
let superView = contentView
usernameTextFild.snp_makeConstraints { (make) in
make.left.equalTo(superView).offset(20)
make.top.equalTo(superView).offset(10)
make.width.equalTo(200)
make.height.equalTo(30)
}
}
}
| mit | fd3c7c5e643c5b4fee1809064800d10c | 23.027778 | 56 | 0.608092 | 4.601064 | false | false | false | false |
nineteen-apps/swift | lessons-02/lesson1/Sources/cpf.swift | 1 | 2158 | // -*-swift-*-
// The MIT License (MIT)
//
// Copyright (c) 2017 - Nineteen
//
// 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: 2017-06-20 by Ronaldo Faria Lima
//
// This file purpose: Classe que realiza o cálculo do dígito verificador do CPF
// para verificação de sua validade.
import Foundation
class CPF: Checksum {
override func calculateCheckDigits() -> Int? {
if let firstDigit = calculateCheckDigit(for: 10), let secondDigit = calculateCheckDigit(for: 11) {
return firstDigit * 10 + secondDigit
}
return nil
}
private func calculateCheckDigit(for weight: Int) -> Int? {
var ckDigit = 0
var currWeight = weight
for i in data.characters.indices {
if currWeight < 1 {
break
}
if let digit = Int(String(data[i])) {
ckDigit += digit * currWeight
} else {
return nil
}
currWeight -= 1
}
let remainder = ckDigit % 11
ckDigit = remainder < 2 ? 0 : 11 - remainder
return ckDigit
}
}
| mit | 0a03eb1b077e445e359de154220245b5 | 36.789474 | 106 | 0.662953 | 4.404908 | false | false | false | false |
lucaslt89/simpsonizados | simpsonizados/simpsonizados/ViewControllers/SeasonViewController.swift | 1 | 4360 | //
// SeasonViewController.swift
// simpsonizados
//
// Created by Lucas Diez de Medina on 1/16/16.
// Copyright © 2016 technopix. All rights reserved.
//
import UIKit
import AVKit
import AlamofireImage
let ShowSeasonViewControllerSegueIdentifier = "ShowSeasonViewController"
class SeasonViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var season: Int!
var chapters: [Chapter]!
private struct Cells {
static let ChapterCellIdentifier : String = "ChapterCellIdentifier"
}
// MARK: - UIView Lifecycle -
override func viewDidLoad() {
super.viewDidLoad()
chapters = DatabaseManager.sharedInstance.retrieveChaptersOfSeason(season)
}
// MARK: - UITableViewDelegate and DataSource methods -
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chapters.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let selectedChapter = chapters[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier(Cells.ChapterCellIdentifier) as! ChapterTableViewCell
cell.nameLabel.text = selectedChapter.name
cell.descriptionLabel.text = selectedChapter.chapterDescription
if let imageUrlString = selectedChapter.imageURL {
cell.chapterImageView.af_setImageWithURL(NSURL(string: imageUrlString)!)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let selectedChapter = chapters[indexPath.row]
if let uniqueVersionURL = extractUniqueURLFromChapter(selectedChapter) {
playVideoFromURL(uniqueVersionURL)
}
else {
showSelectVersionAlertForChapter(selectedChapter)
}
}
// MARK: - Play Video methods -
private func showSelectVersionAlertForChapter(chapter:Chapter) {
let alertController = UIAlertController(title: "Select a language", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
if let latinoURL = chapter.latinoURL where !latinoURL.isEmpty {
let action = UIAlertAction(title: "Español Latino", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.playVideoFromURL(latinoURL)
})
alertController.addAction(action)
}
if let spanishURL = chapter.spanishURL where !spanishURL.isEmpty {
let action = UIAlertAction(title: "Español", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.playVideoFromURL(spanishURL)
})
alertController.addAction(action)
}
if let englishURL = chapter.englishURL where !englishURL.isEmpty {
let action = UIAlertAction(title: "English", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.playVideoFromURL(englishURL)
})
alertController.addAction(action)
}
let action = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Destructive, handler: { (action) -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
})
alertController.addAction(action)
presentViewController(alertController, animated: true, completion: nil)
}
private func extractUniqueURLFromChapter(chapter: Chapter) -> String? {
if chapter.latinoURL != nil && chapter.spanishURL == nil && chapter.englishURL == nil {
return chapter.latinoURL!
}
else if chapter.latinoURL == nil && chapter.spanishURL != nil && chapter.englishURL == nil {
return chapter.spanishURL!
}
else if chapter.latinoURL == nil && chapter.spanishURL == nil && chapter.englishURL != nil {
return chapter.englishURL!
}
return nil
}
private func playVideoFromURL(url: String) {
let avPlayerController = AVPlayerViewController()
avPlayerController.player = AVPlayer(URL: NSURL(string: url)!)
avPlayerController.player?.play()
navigationController?.pushViewController(avPlayerController, animated: true)
}
}
| mit | f6210ccb7adffa38e13bdf38a8abc6da | 35.923729 | 135 | 0.680514 | 5.281212 | false | false | false | false |
adrfer/swift | stdlib/public/core/LazySequence.swift | 2 | 7919 | //===--- LazySequence.swift -----------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A sequence on which normally-eager operations such as `map` and
/// `filter` are implemented lazily.
///
/// Lazy sequences can be used to avoid needless storage allocation
/// and computation, because they use an underlying sequence for
/// storage and compute their elements on demand. For example,
///
/// [1, 2, 3].lazy.map { $0 * 2 }
///
/// is a sequence containing { `2`, `4`, `6` }. Each time an element
/// of the lazy sequence is accessed, an element of the underlying
/// array is accessed and transformed by the closure.
///
/// Sequence operations taking closure arguments, such as `map` and
/// `filter`, are normally eager: they use the closure immediately and
/// return a new array. Using the `lazy` property gives the standard
/// library explicit permission to store the closure and the sequence
/// in the result, and defer computation until it is needed.
///
/// To add new lazy sequence operations, extend this protocol with
/// methods that return lazy wrappers that are themselves
/// `LazySequenceType`s. For example, given an eager `scan`
/// method defined as follows
///
/// extension SequenceType {
/// /// Returns an array containing the results of
/// ///
/// /// p.reduce(initial, combine: combine)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// (1..<6).scan(0, combine: +) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(N)
/// func scan<ResultElement>(
/// initial: ResultElement,
/// @noescape combine: (ResultElement, Generator.Element) -> ResultElement
/// ) -> [ResultElement] {
/// var result = [initial]
/// for x in self {
/// result.append(combine(result.last!, x))
/// }
/// return result
/// }
/// }
///
/// we can build a sequence that lazily computes the elements in the
/// result of `scan`:
///
/// struct LazyScanGenerator<Base: GeneratorType, ResultElement>
/// : GeneratorType {
/// mutating func next() -> ResultElement? {
/// return nextElement.map { result in
/// nextElement = base.next().map { combine(result, $0) }
/// return result
/// }
/// }
/// private var nextElement: ResultElement? // The next result of next().
/// private var base: Base // The underlying generator.
/// private let combine: (ResultElement, Base.Element) -> ResultElement
/// }
///
/// struct LazyScanSequence<Base: SequenceType, ResultElement>
/// : LazySequenceType // Chained operations on self are lazy, too
/// {
/// func generate() -> LazyScanGenerator<Base.Generator, ResultElement> {
/// return LazyScanGenerator(
/// nextElement: initial, base: base.generate(), combine: combine)
/// }
/// private let initial: ResultElement
/// private let base: Base
/// private let combine:
/// (ResultElement, Base.Generator.Element) -> ResultElement
/// }
///
/// and finally, we can give all lazy sequences a lazy `scan` method:
///
/// extension LazySequenceType {
/// /// Returns a sequence containing the results of
/// ///
/// /// p.reduce(initial, combine: combine)
/// ///
/// /// for each prefix `p` of `self`, in order from shortest to
/// /// longest. For example:
/// ///
/// /// Array((1..<6).lazy.scan(0, combine: +)) // [0, 1, 3, 6, 10, 15]
/// ///
/// /// - Complexity: O(1)
/// func scan<ResultElement>(
/// initial: ResultElement,
/// combine: (ResultElement, Generator.Element) -> ResultElement
/// ) -> LazyScanSequence<Self, ResultElement> {
/// return LazyScanSequence(
/// initial: initial, base: self, combine: combine)
/// }
/// }
///
/// - See also: `LazySequence`, `LazyCollectionType`, `LazyCollection`
///
/// - Note: The explicit permission to implement further operations
/// lazily applies only in contexts where the sequence is statically
/// known to conform to `LazySequenceType`. Thus, side-effects such
/// as the accumulation of `result` below are never unexpectedly
/// dropped or deferred:
///
/// extension SequenceType where Generator.Element == Int {
/// func sum() -> Int {
/// var result = 0
/// _ = self.map { result += $0 }
/// return result
/// }
/// }
///
/// [We don't recommend that you use `map` this way, because it
/// creates and discards an array. `sum` would be better implemented
/// using `reduce`].
public protocol LazySequenceType : SequenceType {
/// A `SequenceType` that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// - See also: `elements`
associatedtype Elements: SequenceType = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing an extra
/// `LazySequence` layer. For example,
///
/// _prext_ example needed
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements { get }
var array: [Generator.Element] { get }
}
extension LazySequenceType {
@available(*, unavailable, message="please construct an Array from your lazy sequence: Array(...)")
public var array: [Generator.Element] { fatalError("unavailable") }
}
/// When there's no special associated `Elements` type, the `elements`
/// property is provided.
extension LazySequenceType where Elements == Self {
/// Identical to `self`.
public var elements: Self { return self }
}
/// A sequence containing the same elements as a `Base` sequence, but
/// on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceType`
public struct LazySequence<Base : SequenceType>
: LazySequenceType, _SequenceWrapperType {
/// Creates a sequence that has the same elements as `base`, but on
/// which some operations such as `map` and `filter` are implemented
/// lazily.
public init(_ base: Base) {
self._base = base
}
public var _base: Base
/// The `Base` (presumably non-lazy) sequence from which `self` was created.
public var elements: Base { return _base }
@available(*, unavailable, renamed="Base")
public typealias S = Void
}
extension SequenceType {
/// A sequence containing the same elements as a `Base` sequence,
/// but on which some operations such as `map` and `filter` are
/// implemented lazily.
///
/// - See also: `LazySequenceType`, `LazySequence`
public var lazy: LazySequence<Self> {
return LazySequence(self)
}
}
/// Avoid creating multiple layers of `LazySequence` wrapper.
/// Anything conforming to `LazySequenceType` is already lazy.
extension LazySequenceType {
/// Identical to `self`.
public var lazy: Self {
return self
}
}
@available(*, unavailable, message="Please use the sequence's '.lazy' property")
public func lazy<Base : SequenceType>(s: Base) -> LazySequence<Base> {
fatalError("unavailable")
}
| apache-2.0 | 129e4b51708eaffecf7c9a1f58aa07eb | 36.004673 | 101 | 0.621164 | 4.280541 | false | false | false | false |
rgravina/tddtris | TddTetris/Components/Game/RotateTetrominoAction.swift | 1 | 1171 | class RotateTetrominoAction : Action {
let view: GameView
let state: GameState
let collisionDetector: CollisionDetector
init(
view: GameView,
state: GameState,
collisionDetector: CollisionDetector
) {
self.view = view
self.state = state
self.collisionDetector = collisionDetector
}
func perform() {
if (state.tetromino == nil) {
return
}
if (!collisionDetector.canRotate()) {
return
}
let tetromino = state.tetromino!
let rotatedTetromino = tetromino.rotate()
state.tetromino = rotatedTetromino
for position in tetromino.blocks {
state.free(
position: Position(
column: position.column,
row: position.row
))
}
for position in rotatedTetromino.blocks {
state.occupy(
position: Position(
column: position.column,
row: position.row
))
}
view.move(rotatedTetromino)
view.display(rotatedTetromino)
}
}
| mit | aec4897ca4be346687a3fad0da6877cd | 26.232558 | 50 | 0.532024 | 5.446512 | false | false | false | false |
itsjingun/govhacknz_mates | Mates/Data/Models/MTSGroup.swift | 1 | 636 | //
// MTSGroup.swift
// Mates
//
// Created by Eddie Chae on 4/07/15.
// Copyright (c) 2015 Governmen. All rights reserved.
//
import Foundation
class MTSGroup: MTSBaseModel {
var id: String!
var owner: MTSUserProfile!
var users: Array<MTSUserProfile>!
var userUsernames: Array<String>!
var location: String!
init(id: String!, owner: MTSUserProfile!, users: Array<MTSUserProfile>!, userUsernames: Array<String>!, location: String!) {
self.id = id
self.owner = owner
self.users = users
self.userUsernames = userUsernames
self.location = location
}
} | gpl-2.0 | 7292ea784f5b60c6b9d0057a91c7e41a | 22.592593 | 128 | 0.639937 | 3.763314 | false | false | false | false |
auth0/Lock.iOS-OSX | Lock/MultifactorPresenter.swift | 2 | 3163 | // MultifactorPresenter.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
class MultifactorPresenter: Presentable, Loggable {
var interactor: MultifactorAuthenticatable
let database: DatabaseConnection
var customLogger: Logger?
var navigator: Navigable
init(interactor: MultifactorAuthenticatable, connection: DatabaseConnection, navigator: Navigable) {
self.interactor = interactor
self.database = connection
self.navigator = navigator
}
var messagePresenter: MessagePresenter?
var view: View {
let view = MultifactorCodeView()
let form = view.form
view.form?.onValueChange = { input in
self.messagePresenter?.hideCurrent()
guard case .oneTimePassword = input.type else { return }
do {
try self.interactor.setMultifactorCode(input.text)
input.showValid()
} catch let error as InputValidationError {
input.showError(error.localizedMessage(withConnection: self.database))
} catch {
input.showError()
}
}
let action = { [weak form] (button: PrimaryButton) in
self.messagePresenter?.hideCurrent()
self.logger.debug("resuming with mutifactor code: \(self.interactor.code.verbatim())")
let interactor = self.interactor
button.inProgress = true
interactor.login { error in
Queue.main.async {
button.inProgress = false
form?.needsToUpdateState()
if let error = error {
self.messagePresenter?.showError(error)
self.logger.error("Failed with error \(error)")
}
}
}
}
view.form?.onReturn = { [unowned view]_ in
guard let button = view.primaryButton else { return }
action(button)
}
view.primaryButton?.onPress = action
return view
}
}
| mit | 795d43ba245fb4e75d9fa2955a1e9ae8 | 39.037975 | 104 | 0.644325 | 5.06891 | false | false | false | false |
chanhx/Octogit | iGithub/ViewControllers/SyntaxHighlightSettingsViewController.swift | 2 | 3063 | //
// SyntaxHighlightSettingsViewController.swift
// iGithub
//
// Created by Chan Hocheung on 9/4/16.
// Copyright © 2016 Hocheung. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SyntaxHighlightSettingsViewController: UITableViewController {
@IBOutlet weak var themeLabel: UILabel!
@IBOutlet weak var lineNumbersSwitch: UISwitch!
let webViewCell = WebViewCell()
let userDefaults = UserDefaults.standard
let disposeBag = DisposeBag()
lazy var themes: [String] = {
let path = Bundle.main.path(forResource: "themes", ofType: "plist")
return NSArray(contentsOfFile: path!) as! [String]
}()
let sample: String = {
let path = Bundle.main.path(forResource: "sample", ofType: "")
return try! String(contentsOfFile: path!, encoding: String.Encoding.utf8)
}()
var rendering: String {
return Renderer.render(sample, language: "c", theme: themeLabel.text, showLineNumbers: lineNumbersSwitch.isOn)
}
lazy var pickerView: OptionPickerView = OptionPickerView(delegate:self)
override func viewDidLoad() {
super.viewDidLoad()
themeLabel.text = userDefaults.object(forKey: Constants.kTheme) as? String
lineNumbersSwitch.isOn = userDefaults.bool(forKey: Constants.kLineNumbers)
webViewCell.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 230)
webViewCell.webView.isOpaque = false
tableView.tableFooterView = webViewCell
pickerView.selectedRows[0] = self.themes.firstIndex(of: self.themeLabel.text!) ?? 0
lineNumbersSwitch.rx.value.asDriver()
.drive(onNext: { [unowned self] _ in
self.renderSample()
})
.disposed(by: disposeBag)
}
override func viewDidDisappear(_ animated: Bool) {
userDefaults.set(themeLabel.text, forKey: Constants.kTheme)
userDefaults.set(lineNumbersSwitch.isOn, forKey: Constants.kLineNumbers)
super.viewDidDisappear(animated)
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard indexPath.row == 0 else {
return
}
self.pickerView.show()
}
func renderSample() {
webViewCell.webView.loadHTMLString(rendering, baseURL: Bundle.main.resourceURL)
}
}
extension SyntaxHighlightSettingsViewController: OptionPickerViewDelegate {
func doneButtonClicked(_ pickerView: OptionPickerView) {
themeLabel.text = themes[pickerView.selectedRows[0]]
renderSample()
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return themes.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return themes[row]
}
}
| gpl-3.0 | 16dc377fc280f409c4db43df726c8d10 | 30.895833 | 118 | 0.65676 | 4.844937 | false | false | false | false |
iyergkris/step-oracle | iPhone/FitnessFortuna/FitnessFortuna WatchKit Extension/InterfaceController.swift | 1 | 7169 | //
// InterfaceController.swift
// FitnessFortuna WatchKit Extension
//
// Created by Vikas Iyer on 11/3/15.
// Copyright © 2015 VI. All rights reserved.
//
//
import WatchKit
import Foundation
import HealthKit
import WatchConnectivity
class InterfaceController: WKInterfaceController, HKWorkoutSessionDelegate, WCSessionDelegate {
@IBOutlet var dateLabel: WKInterfaceLabel!
let healthStore = HKHealthStore()
let workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.Walking, locationType: HKWorkoutSessionLocationType.Indoor)
let stepCountUnit = HKUnit(fromString: "")
var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor))
var content:String = String.init("")
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
workoutSession.delegate = self
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
//if WCSession.isSupported(){
//let connectivitySession = WCSession.defaultSession()
//connectivitySession.delegate = self
//connectivitySession.activateSession()
//}
guard HKHealthStore.isHealthDataAvailable() == true else {
//label.setText("not available")
print("healthdata not available")
return
}
guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else{
displayNotAllowed()
return
}
let dataTypes = Set(arrayLiteral: quantityType)
healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypes) {(success, error) -> Void in
if success == false {
// displayNotAllowed
print(error)
self.displayNotAllowed()
}
}
}
func displayNotAllowed(){
print("displayNotAllowed")
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate){
switch toState {
case .Running:
workoutDidStart(date)
case .Ended:
workoutDidStop(date)
default:
print("Unexpected statev\(toState)")
}
}
func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError){
}
func workoutDidStart(date:NSDate){
if let query = createStepCountStreamingQuery(date){
healthStore.executeQuery(query)
} else {
// cannot start
}
}
func workoutDidStop(date:NSDate){
if let query = createStepCountStreamingQuery(date){
healthStore.stopQuery(query)
}
else {
// cannot stop
}
}
func createStepCountStreamingQuery(workoutStartDate:NSDate) -> HKQuery? {
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else { return nil}
let past = NSDate.distantPast()
let now = NSDate()
//let timePredicate = NSPredicate.init();
let timePredicate = HKQuery.predicateForSamplesWithStartDate(past, endDate: now, options: .None)
// let timePredicate:NSPredicate = NSPredicate.init(format: "(date <= %@) AND (date >= %@)", workoutStartDate, workoutStartDate.dateByAddingTimeInterval(-900))
let stepCountQuery = HKAnchoredObjectQuery(type:quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit))
{ (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
//print("sampledObjects \(sampleObjects)")
guard let newAnchor = newAnchor else {return}
self.anchor = newAnchor
self.updateStepCount(sampleObjects)
}
stepCountQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in
self.anchor = newAnchor!
self.updateStepCount(samples)
}
return stepCountQuery
}
func updateStepCount(samples: [HKSample]?){
guard let stepCountSamples = samples as? [HKQuantitySample] else {return}
dispatch_async(dispatch_get_main_queue()){
guard let sample = stepCountSamples.first else {return}
let value = sample.quantity.doubleValueForUnit(self.stepCountUnit)
// update label
//print("value \(value)")
let timeStamp = sample.startDate
let endTimeStamp = sample.endDate
let dateFormatter:NSDateFormatter = NSDateFormatter.init()
dateFormatter.dateFormat = "yy/MM/dd HH:mm"
let formattedDateString:String = dateFormatter.stringFromDate(sample.startDate)
self.dateLabel.setText(formattedDateString)
print(formattedDateString, value)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let fileName:String = "\(documentsPath)/textfile.txt"
print("fileName: \(fileName)")
//var content:String = "\(formattedDateString), \(value)"
self.content.appendContentsOf("\(formattedDateString), \(value)\n")
//content.append("\(formattedDateString), \(value)")
//content.writeToFile(fileName, atomically: false, encoding: <#T##NSStringEncoding#>)
do {
try self.content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {
print("error writingToFile")
}
// retrieve source from apple?
let name = sample.sourceRevision.source.name
//update name?
//print("name \(name)")
}
}
@IBAction func trackStepCount() {
healthStore.startWorkoutSession(workoutSession)
}
@IBAction func stopTracking() {
healthStore.endWorkoutSession(workoutSession)
let connectivitySession:WCSession = WCSession.defaultSession()
//var error:NSError
connectivitySession.sendMessage(["getHealthData":"message"], replyHandler: nil, errorHandler: nil)
}
func changeDateFormat(date:NSDate){
}
}
| agpl-3.0 | 5217c6faebcbc9319b3e903bf849facd | 31.730594 | 167 | 0.592076 | 6.013423 | false | true | false | false |
Finb/V2ex-Swift | Controller/RelevantCommentsViewController.swift | 1 | 6538 | //
// RelevantCommentsViewController.swift
// V2ex-Swift
//
// Created by huangfeng on 3/3/16.
// Copyright © 2016 Fin. All rights reserved.
//
import UIKit
import FXBlurView
import Shimmer
class RelevantCommentsNav:V2EXNavigationController , UIViewControllerTransitioningDelegate {
override init(nibName : String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "", bundle: nil)
}
init(comments:[TopicCommentModel]) {
let viewController = RelevantCommentsViewController()
viewController.commentsArray = comments
super.init(rootViewController: viewController)
self.transitioningDelegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return RelevantCommentsViewControllerTransionPresent()
}
}
class RelevantCommentsViewControllerTransionPresent:NSObject,UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! RelevantCommentsNav
let container = transitionContext.containerView
container.addSubview(toVC.view)
toVC.view.alpha = 0
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: UIView.AnimationOptions.curveEaseIn, animations: { () -> Void in
toVC.view.alpha = 1
}) { (finished: Bool) -> Void in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
}
class RelevantCommentsViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var commentsArray:[TopicCommentModel] = []
fileprivate var dismissing = false
fileprivate lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.cancelEstimatedHeight()
tableView.separatorStyle = .none
if #available(iOS 11.0, *) {
tableView.contentInsetAdjustmentBehavior = .never
}
tableView.backgroundColor = UIColor.clear
tableView.contentInset = UIEdgeInsets(top: 64, left: 0, bottom: 0, right: 0)
regClass(tableView, cell: TopicDetailCommentCell.self)
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
var frostedView = FXBlurView()
override func viewDidLoad() {
super.viewDidLoad()
frostedView.underlyingView = V2Client.sharedInstance.centerNavigation!.view
frostedView.isDynamic = false
frostedView.blurRadius = 35
frostedView.tintColor = UIColor.black
frostedView.frame = self.view.frame
self.view.addSubview(frostedView)
let shimmeringView = FBShimmeringView()
shimmeringView.isShimmering = true
shimmeringView.shimmeringOpacity = 0.3
shimmeringView.shimmeringSpeed = 45
shimmeringView.shimmeringHighlightLength = 0.6
self.view.addSubview(shimmeringView)
let label = UILabel(frame: shimmeringView.frame)
label.text = "下拉关闭查看"
label.font = UIFont(name: "HelveticaNeue-Light", size: 12)
if V2EXColor.sharedInstance.style == V2EXColor.V2EXColorStyleDefault {
label.textColor = UIColor.black
}
else{
label.textColor = UIColor.white
}
label.textAlignment = .center
label.backgroundColor = UIColor.clear
shimmeringView.contentView = label
var y:CGFloat = 15
if UIDevice.current.isIphoneX {
y = 24
}
shimmeringView.frame = CGRect( x: (SCREEN_WIDTH-80) / 2 , y: y, width: 80, height: 44)
self.view.addSubview(self.tableView);
self.tableView.snp.remakeConstraints{ (make) -> Void in
make.left.right.equalTo(self.view);
make.height.equalTo(self.view)
make.top.equalTo(self.view.snp.bottom)
}
self.tableView.v2_scrollToBottom()
}
override func viewDidAppear(_ animated: Bool) {
self.tableView.snp.remakeConstraints{ (make) -> Void in
make.left.right.equalTo(self.view);
make.height.equalTo(self.view)
make.top.equalTo(self.view)
}
UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 8, options: UIView.AnimationOptions.curveLinear, animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
(self.navigationController as! V2EXNavigationController).navigationBarAlpha = 0
}
override func viewWillDisappear(_ animated: Bool) {
if !self.dismissing{
(self.navigationController as! V2EXNavigationController).navigationBarAlpha = 1
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.commentsArray.count;
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let layout = self.commentsArray[indexPath.row].textLayout!
return layout.textBoundingSize.height + 12 + 35 + 12 + 12 + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = getCell(tableView, cell: TopicDetailCommentCell.self, indexPath: indexPath)
cell.bind(self.commentsArray[indexPath.row])
return cell
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
//下拉关闭
if scrollView.contentOffset.y <= -100 {
//让scrollView 不弹跳回来
scrollView.contentInset = UIEdgeInsets(top: -1 * scrollView.contentOffset.y, left: 0, bottom: 0, right: 0)
scrollView.isScrollEnabled = false
self.navigationController!.dismiss(animated: true, completion: nil)
self.dismissing = true
}
}
}
| mit | 64d1e1661ce352cba70e58bd8ad3029b | 38.186747 | 178 | 0.668563 | 5.19984 | false | false | false | false |
naokits/my-programming-marathon | RxSwiftDemo/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/SimpleValidation/SimpleValidationViewController.swift | 2 | 2254 | //
// SimpleValidationViewController.swift
// RxExample
//
// Created by Krunoslav Zaher on 12/6/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
let minimalUsernameLength = 5
let minimalPasswordLength = 5
class SimpleValidationViewController : ViewController {
@IBOutlet weak var usernameOutlet: UITextField!
@IBOutlet weak var usernameValidOutlet: UILabel!
@IBOutlet weak var passwordOutlet: UITextField!
@IBOutlet weak var passwordValidOutlet: UILabel!
@IBOutlet weak var doSomethingOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
usernameValidOutlet.text = "Username has to be at least \(minimalUsernameLength) characters"
passwordValidOutlet.text = "Username has to be at least \(minimalPasswordLength) characters"
let usernameValid = usernameOutlet.rx_text
.map { $0.characters.count >= minimalUsernameLength }
.shareReplay(1) // without this map would be executed once for each binding, rx is stateless by default
let passwordValid = passwordOutlet.rx_text
.map { $0.characters.count >= minimalPasswordLength }
.shareReplay(1)
let everythingValid = Observable.combineLatest(usernameValid, passwordValid) { $0 && $1 }
.shareReplay(1)
usernameValid
.bindTo(passwordOutlet.rx_enabled)
.addDisposableTo(disposeBag)
usernameValid
.bindTo(usernameValidOutlet.rx_hidden)
.addDisposableTo(disposeBag)
passwordValid
.bindTo(passwordValidOutlet.rx_hidden)
.addDisposableTo(disposeBag)
everythingValid
.bindTo(doSomethingOutlet.rx_enabled)
.addDisposableTo(disposeBag)
doSomethingOutlet.rx_tap
.subscribeNext { [weak self] in self?.showAlert() }
.addDisposableTo(disposeBag)
}
func showAlert() {
let alertView = UIAlertView(
title: "RxExample",
message: "This is wonderful",
delegate: nil,
cancelButtonTitle: "OK"
)
alertView.show()
}
} | mit | 3a4307f866b1f35ef6c06b50bb820168 | 27.897436 | 115 | 0.659121 | 5.006667 | false | false | false | false |
mbeloded/discountsPublic | discounts/Classes/UI/CategoryView/CategoryViewController.swift | 1 | 1292 | //
// CategoryViewController.swift
// discounts
//
// Created by Michael Bielodied on 9/10/14.
// Copyright (c) 2014 Michael Bielodied. All rights reserved.
//
import UIKit
class CategoryViewController: UIViewController {
@IBOutlet private var categoryView: CategoryView!
override func viewDidLoad() {
super.viewDidLoad()
categoryView.setupView()
categoryView.owner = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
if (segue.identifier == "ShowMainMenu") {
let viewController:MainMenuViewController = segue.destination as! MainMenuViewController
viewController.categoryIndex = CategoryManager.sharedInstance.categoryArrayData[categoryView.getSelectedItem()].categoryId
}
}
}
| gpl-3.0 | 08c86337b76b16a5cd70d8673e162450 | 32.128205 | 138 | 0.698142 | 5.230769 | false | false | false | false |
Rag0n/QuNotes | QuNotes/Notebook/NotebookViewController.swift | 1 | 7914 | //
// NotebookViewController.swift
// QuNotes
//
// Created by Alexander Guschin on 17.06.17.
// Copyright © 2017 Alexander Guschin. All rights reserved.
//
import UIKit
import Prelude
import FlexLayout
final public class NotebookViewController: UIViewController {
public func perform(effect: Notebook.ViewEffect) {
switch effect {
case let .updateAllNotes(notes):
self.notes = notes
tableView.reloadData()
case .hideBackButton:
navigationItem.setHidesBackButton(true, animated: true)
case .showBackButton:
navigationItem.setHidesBackButton(false, animated: true)
case let .updateTitle(title):
titleTextField.text = title
case .focusOnTitle:
titleTextField.becomeFirstResponder()
case let .deleteNote(index, notes):
self.notes = notes
let indexPath = IndexPath(row: index, section: 0)
tableView.deleteRows(at: [indexPath], with: .automatic)
case let .addNote(index, notes):
self.notes = notes
let indexPath = IndexPath(row: index, section: 0)
tableView.insertRows(at: [indexPath], with: .automatic)
}
}
public init(withDispatch dispatch: @escaping Notebook.ViewDispacher) {
self.dispatch = dispatch
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func loadView() {
view = UIView()
view.flex.alignItems(.center).define {
$0.addItem(tableView).grow(1)
$0.addItem(addButton).position(.absolute).bottom(20)
}
setupNavigationBar()
tableView.dataSource = self
tableView.delegate = self
}
public override func viewDidLoad() {
super.viewDidLoad()
dispatch <| .didLoad
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
view.flex.layout()
}
override public func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
guard traitCollection.preferredContentSizeCategory != previousTraitCollection?.preferredContentSizeCategory else { return }
addButton.flex.markDirty()
}
// MARK: - Private
fileprivate enum Constants {
static let estimatedCellHeight: CGFloat = 44
static let notebookCellReuseIdentifier = "notebookCellReuseIdentifier"
}
fileprivate var dispatch: Notebook.ViewDispacher
fileprivate var notes: [Notebook.NoteViewModel] = []
private lazy var searchController: UISearchController = {
let s = UISearchController(searchResultsController: nil)
s.searchResultsUpdater = self
s.dimsBackgroundDuringPresentation = false
self.definesPresentationContext = true
self.navigationItem.searchController = s
return s
}()
private let tableView: UITableView = {
let t = UITableView()
NotebookTableViewCell.registerFor(tableView: t, reuseIdentifier: Constants.notebookCellReuseIdentifier)
t.estimatedRowHeight = Constants.estimatedCellHeight
let theme = AppEnvironment.current.theme
t.backgroundColor = theme.ligherDarkColor
t.separatorColor = theme.textColor.withAlphaComponent(0.5)
return t
}()
private let addButton: UIButton = {
let b = UIButton(type: .system)
b.setTitle("notebook_add_note_button".localized, for: .normal)
b.titleLabel!.font = UIFont.preferredFont(forTextStyle: .headline)
b.titleLabel!.adjustsFontForContentSizeCategory = true
b.addTarget(self, action: #selector(addNote), for: .touchUpInside)
return b
}()
private let titleTextField: UITextField = {
let t = UITextField(frame: CGRect(x: 0, y: 0, width: 120, height: 22))
t.textAlignment = .center
t.keyboardAppearance = .dark
t.returnKeyType = .done
t.keyboardType = .asciiCapable
let attributes = [NSAttributedStringKey.foregroundColor: AppEnvironment.current.theme.textColor.withAlphaComponent(0.55)]
t.attributedPlaceholder = NSAttributedString(string: "notebook_title_placeholder".localized,
attributes: attributes)
return t
}()
private func setupNavigationBar() {
addTitleTextField()
addDeleteButton()
addSearchController()
}
private func addTitleTextField() {
titleTextField.delegate = self
navigationItem.titleView = titleTextField
}
private func addDeleteButton() {
let deleteButton = UIBarButtonItem(barButtonSystemItem: .trash,
target: self,
action: #selector(onDeleteButtonClick))
self.navigationItem.rightBarButtonItem = deleteButton
}
private func addSearchController() {
searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
navigationItem.searchController = searchController
}
@objc private func addNote() {
dispatch <| .addNote
}
@objc private func onDeleteButtonClick() {
dispatch <| .deleteNotebook
}
}
// MARK: - UITableViewDataSource
extension NotebookViewController: UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notes.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Constants.notebookCellReuseIdentifier,
for: indexPath) as! NotebookTableViewCell
cell.render(with: notes[indexPath.row])
return cell
}
}
// MARK: - UITableViewDelegate
extension NotebookViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dispatch <| .selectNote(index: indexPath.row)
tableView.deselectRow(at: indexPath, animated: true)
}
public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = deleteContextualAction(forIndexPath: indexPath)
let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
return configuration
}
private func deleteContextualAction(forIndexPath indexPath: IndexPath) -> UIContextualAction {
let action = UIContextualAction(style: .destructive, title: "notebook_delete_note_button".localized) { [unowned self] (action, view, success) in
self.dispatch <| .deleteNote(index: indexPath.row)
success(true)
}
action.backgroundColor = .red
return action
}
}
// MARK: - UISearchResultsUpdating
extension NotebookViewController: UISearchResultsUpdating {
public func updateSearchResults(for searchController: UISearchController) {
dispatch <| .filterNotes(filter: searchController.searchBar.text)
}
}
// MARK: - UITextField
extension NotebookViewController: UITextFieldDelegate {
public func textFieldDidBeginEditing(_ textField: UITextField) {
dispatch <| .didStartToEditTitle
}
public func textFieldDidEndEditing(_ textField: UITextField) {
dispatch <| .didFinishToEditTitle(newTitle: textField.text)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| gpl-3.0 | 9d50311fe1ca06addc97aacfc99a58e7 | 35.298165 | 152 | 0.671932 | 5.580395 | false | false | false | false |
drewcrawford/XcodeServerSDK | XcodeServerSDKTests/DevicesTests.swift | 3 | 2624 | //
// DevicesTests.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 13/07/15.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import XCTest
import XcodeServerSDK
class DevicesTests: XCTestCase {
let macMini = Device(json: [
"osVersion" : "10.11",
"connected" : true,
"simulator" : false,
"modelCode" : "Macmini6,1",
"deviceType" : "com.apple.mac",
"modelName" : "Mac mini",
"_id" : "1ad0e8785cacca73d980cdb23600383e",
"modelUTI" : "com.apple.macmini-unibody-no-optical",
"doc_type" : "device",
"trusted" : true,
"name" : "bozenka",
"supported" : true,
"processor" : "2,5 GHz Intel Core i5",
"identifier" : "FFFFFFFF-0F3C-5893-AF8A-D9CFF068B82C-x86_64",
"enabledForDevelopment" : true,
"serialNumber" : "C07JT7H5DWYL",
"platformIdentifier" : "com.apple.platform.macosx",
"_rev" : "3-6a49ba8135f3f4ddcbaefe1b469f479c",
"architecture" : "x86_64",
"retina" : false,
"isServer" : true,
"tinyID" : "7DCD98A"
])
func testDictionarify() {
let expected = [ "device_id": "1ad0e8785cacca73d980cdb23600383e" ]
XCTAssertEqual(macMini.dictionarify(), expected)
}
func testGetDevices() {
let expectation = self.expectationWithDescription("Get Devices")
let server = self.getRecordingXcodeServer("get_devices")
server.getDevices { (devices, error) -> () in
XCTAssertNil(error)
XCTAssertNotNil(devices)
if let devices = devices {
XCTAssertEqual(devices.count, 15, "There should be 15 devices")
XCTAssertEqual(devices.filter { $0.platform == DevicePlatform.PlatformType.iOS }.count, 2, "There should be 2 real iPhones")
XCTAssertEqual(devices.filter { $0.platform == DevicePlatform.PlatformType.OSX }.count, 2, "There should be 2 real Macs")
XCTAssertEqual(devices.filter { $0.platform == DevicePlatform.PlatformType.iOS_Simulator }.count, 9, "There should be 9 iOS simulators")
XCTAssertEqual(devices.filter { $0.platform == DevicePlatform.PlatformType.watchOS_Simulator }.count, 2, "There should be 2 watchOS simulators")
XCTAssertEqual(devices.filter { $0.activeProxiedDevice != nil }.count, 2, "There should be 2 active proxied devices (watchOS)")
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(10.0, handler: nil)
}
}
| mit | 487ea00c7afb5e7ae4d248d65104b4bb | 38.134328 | 160 | 0.605645 | 3.913433 | false | true | false | false |
zmarvin/EnjoyMusic | Pods/Macaw/Source/model/geom2d/Transform.swift | 1 | 2538 | import Foundation
public final class Transform {
public let m11: Double
public let m12: Double
public let m21: Double
public let m22: Double
public let dx: Double
public let dy: Double
public static let identity: Transform = Transform()
public init(m11: Double = 1, m12: Double = 0, m21: Double = 0, m22: Double = 1, dx: Double = 0, dy: Double = 0) {
self.m11 = m11
self.m12 = m12
self.m21 = m21
self.m22 = m22
self.dx = dx
self.dy = dy
}
// GENERATED NOT
public func move(dx: Double, dy: Double) -> Transform {
return Transform(m11: m11, m12: m12, m21: m21, m22: m22,
dx: dx * m11 + dy * m21 + self.dx, dy: dx * m12 + dy * m22 + self.dy)
}
// GENERATED NOT
public func scale(sx: Double, sy: Double) -> Transform {
return Transform(m11: m11 * sx, m12: m12 * sx, m21: m21 * sy, m22: m22 * sy, dx: dx, dy: dy)
}
// GENERATED NOT
public func shear(shx: Double, shy: Double) -> Transform {
return Transform(m11: m11 + m21 * shy, m12: m12 + m22 * shy,
m21: m11 * shx + m21, m22: m12 * shx + m22, dx: dx, dy: dy)
}
// GENERATED NOT
public func rotate(angle: Double) -> Transform {
let asin = sin(angle); let acos = cos(angle)
return Transform(m11: acos * m11 + asin * m21, m12: acos * m12 + asin * m22,
m21: -asin * m11 + acos * m21, m22: -asin * m12 + acos * m22, dx: dx, dy: dy)
}
// GENERATED NOT
public func rotate(angle: Double, x: Double, y: Double) -> Transform {
return move(dx: x, dy: y).rotate(angle: angle).move(dx: -x, dy: -y)
}
// GENERATED
public class func move(dx: Double, dy: Double) -> Transform {
return Transform(dx: dx, dy: dy)
}
// GENERATED
public class func scale(sx: Double, sy: Double) -> Transform {
return Transform(m11: sx, m22: sy)
}
// GENERATED
public class func shear(shx: Double, shy: Double) -> Transform {
return Transform(m12: shy, m21: shx)
}
// GENERATED NOT
public class func rotate(angle: Double) -> Transform {
let asin = sin(angle); let acos = cos(angle)
return Transform(m11: acos, m12: asin, m21: -asin, m22: acos)
}
// GENERATED NOT
public class func rotate(angle: Double, x: Double, y: Double) -> Transform {
return Transform.move(dx: x, dy: y).rotate(angle: angle).move(dx: -x, dy: -y)
}
// GENERATED NOT
public func invert() -> Transform? {
let det = self.m11 * self.m22 - self.m12 * self.m21
if (det == 0) {
return nil
}
return Transform(m11: m22 / det, m12: -m12 / det, m21: -m21 / det, m22: m11 / det,
dx: (m21 * dy - m22 * dx) / det,
dy: (m12 * dx - m11 * dy) / det)
}
}
| mit | 5abc27faae659720f26191dbe63f6f97 | 27.516854 | 114 | 0.627266 | 2.638254 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Browser/BrowserPrompts.swift | 3 | 5169 | /* 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 Foundation
import WebKit
import Shared
@objc protocol JSPromptAlertControllerDelegate: class {
func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController)
}
/// A simple version of UIAlertController that attaches a delegate to the viewDidDisappear method
/// to allow forwarding the event. The reason this is needed for prompts from Javascript is we
/// need to invoke the completionHandler passed to us from the WKWebView delegate or else
/// a runtime exception is thrown.
class JSPromptAlertController: UIAlertController {
var alertInfo: JSAlertInfo?
weak var delegate: JSPromptAlertControllerDelegate?
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
delegate?.promptAlertControllerDidDismiss(self)
}
}
/**
* An JSAlertInfo is used to store information about an alert we want to show either immediately or later.
* Since alerts are generated by web pages and have no upper limit it would be unwise to allocate a
* UIAlertController instance for each generated prompt which could potentially be queued in the background.
* Instead, the JSAlertInfo structure retains the relevant data needed for the prompt along with a copy
* of the provided completionHandler to let us generate the UIAlertController when needed.
*/
protocol JSAlertInfo {
func alertController() -> JSPromptAlertController
func cancel()
}
struct MessageAlert: JSAlertInfo {
let message: String
let frame: WKFrameInfo
let completionHandler: () -> Void
func alertController() -> JSPromptAlertController {
let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame),
message: message,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: Strings.OKString, style: .default) { _ in
self.completionHandler()
})
alertController.alertInfo = self
return alertController
}
func cancel() {
completionHandler()
}
}
struct ConfirmPanelAlert: JSAlertInfo {
let message: String
let frame: WKFrameInfo
let completionHandler: (Bool) -> Void
init(message: String, frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
self.message = message
self.frame = frame
self.completionHandler = completionHandler
}
func alertController() -> JSPromptAlertController {
// Show JavaScript confirm dialogs.
let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: Strings.OKString, style: .default) { _ in
self.completionHandler(true)
})
alertController.addAction(UIAlertAction(title: Strings.CancelString, style: .cancel) { _ in
self.cancel()
})
alertController.alertInfo = self
return alertController
}
func cancel() {
completionHandler(false)
}
}
struct TextInputAlert: JSAlertInfo {
let message: String
let frame: WKFrameInfo
let completionHandler: (String?) -> Void
let defaultText: String?
var input: UITextField!
init(message: String, frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void, defaultText: String?) {
self.message = message
self.frame = frame
self.completionHandler = completionHandler
self.defaultText = defaultText
}
func alertController() -> JSPromptAlertController {
let alertController = JSPromptAlertController(title: titleForJavaScriptPanelInitiatedByFrame(frame), message: message, preferredStyle: .alert)
var input: UITextField!
alertController.addTextField(configurationHandler: { (textField: UITextField) in
input = textField
input.text = self.defaultText
})
alertController.addAction(UIAlertAction(title: Strings.OKString, style: .default) { _ in
self.completionHandler(input.text)
})
alertController.addAction(UIAlertAction(title: Strings.CancelString, style: .cancel) { _ in
self.cancel()
})
alertController.alertInfo = self
return alertController
}
func cancel() {
completionHandler(nil)
}
}
/// Show a title for a JavaScript Panel (alert) based on the WKFrameInfo. On iOS9 we will use the new securityOrigin
/// and on iOS 8 we will fall back to the request URL. If the request URL is nil, which happens for JavaScript pages,
/// we fall back to "JavaScript" as a title.
private func titleForJavaScriptPanelInitiatedByFrame(_ frame: WKFrameInfo) -> String {
var title = "\(frame.securityOrigin.`protocol`)://\(frame.securityOrigin.host)"
if frame.securityOrigin.port != 0 {
title += ":\(frame.securityOrigin.port)"
}
return title
}
| mpl-2.0 | d35683d0f381ec4de40edfdc4788e87f | 37.007353 | 150 | 0.706133 | 5.189759 | false | false | false | false |
inket/stts | stts/Services/Super/AzureDevOpsStore.swift | 1 | 4052 | //
// AzureDevOpsStore.swift
// stts
//
import Kanna
protocol AzureDevOpsStoreService {
var serviceName: String { get }
}
private struct AzureDevOpsDataProviders: Codable {
struct ResponseData: Codable {
struct DataProvider: Codable {
struct DataServiceStatus: Codable {
struct DataService: Codable {
struct DataGeography: Codable {
let name: String
let health: Int
var status: ServiceStatus {
switch health {
case 1: return .major
case 2: return .minor
case 3: return .notice
case 4: return .good
default: return .undetermined
}
}
}
let id: String
let geographies: [DataGeography]
var status: ServiceStatus {
return geographies.map { $0.status }.max() ?? .undetermined
}
}
let services: [DataService]
}
let serviceStatus: DataServiceStatus
}
enum CodingKeys: String, CodingKey {
case dataProvider = "ms.vss-status-web.public-status-data-provider"
}
let dataProvider: DataProvider
}
let data: ResponseData
}
class AzureDevOpsStore: Loading {
private var url = URL(string: "https://status.dev.azure.com")!
private var statuses: [String: ServiceStatus] = [:]
private var loadErrorMessage: String?
private var callbacks: [() -> Void] = []
private var lastUpdateTime: TimeInterval = 0
private var currentlyReloading: Bool = false
func loadStatus(_ callback: @escaping () -> Void) {
callbacks.append(callback)
guard !currentlyReloading else { return }
// Throttling to prevent multiple requests if the first one finishes too quickly
guard Date.timeIntervalSinceReferenceDate - lastUpdateTime >= 3 else { return clearCallbacks() }
currentlyReloading = true
loadData(with: url) { data, _, error in
defer {
self.currentlyReloading = false
self.clearCallbacks()
}
self.statuses = [:]
guard let data = data else { return self._fail(error) }
guard
let doc = try? HTML(html: data, encoding: .utf8),
let json = doc.css("script#dataProviders").first?.innerHTML,
let jsonData = json.data(using: .utf8),
let providers = try? JSONDecoder().decode(AzureDevOpsDataProviders.self, from: jsonData)
else {
return self._fail("Couldn't parse response")
}
providers.data.dataProvider.serviceStatus.services.forEach {
self.statuses[$0.id] = $0.status
}
self.lastUpdateTime = Date.timeIntervalSinceReferenceDate
}
}
func status(for service: AzureDevOpsStoreService) -> (ServiceStatus, String) {
let status: ServiceStatus?
if service.serviceName == "*" {
status = statuses.values.max()
} else {
status = statuses[service.serviceName]
}
switch status {
case .good?: return (.good, "Healthy")
case .minor?: return (.minor, "Degraded")
case .major?: return (.major, "Unhealthy")
case .notice?: return (.notice, "Advisory")
default: return (.undetermined, loadErrorMessage ?? "Unexpected error")
}
}
private func clearCallbacks() {
callbacks.forEach { $0() }
callbacks = []
}
private func _fail(_ error: Error?) {
_fail(ServiceStatusMessage.from(error))
}
private func _fail(_ message: String) {
loadErrorMessage = message
lastUpdateTime = 0
}
}
| mit | aae628d5377641ca0be9dc2e3bedd23d | 29.69697 | 104 | 0.539487 | 5.194872 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/Utils/GutenbergMediaEditorImage.swift | 2 | 2052 | import Foundation
import MediaEditor
/**
This is a struct to be given to MediaEditor that represent the image.
We need the full high-quality image in the Media Editor.
*/
class GutenbergMediaEditorImage: AsyncImage {
private var tasks: [ImageDownloaderTask] = []
private var originalURL: URL
private let post: AbstractPost
private var fullQualityURL: URL? {
guard var urlComponents = URLComponents(url: originalURL, resolvingAgainstBaseURL: false) else {
return nil
}
urlComponents.query = nil
return try? urlComponents.asURL()
}
private lazy var mediaUtility: EditorMediaUtility = {
return EditorMediaUtility()
}()
var thumb: UIImage?
init(url: URL, post: AbstractPost) {
originalURL = url
self.post = post
thumb = AnimatedImageCache.shared.cachedStaticImage(url: originalURL)
}
/**
If a thumbnail doesn't exist in cache, fetch one
*/
func thumbnail(finishedRetrievingThumbnail: @escaping (UIImage?) -> ()) {
let task = ImageDownloader.shared.downloadImage(at: originalURL, completion: { image, error in
guard let image = image else {
finishedRetrievingThumbnail(nil)
return
}
finishedRetrievingThumbnail(image)
})
tasks.append(task)
}
/**
Fetch the full high-quality image
*/
func full(finishedRetrievingFullImage: @escaping (UIImage?) -> ()) {
// By passing .zero as the size the full quality image will be downloaded
let task = mediaUtility.downloadImage(from: fullQualityURL!, size: .zero, scale: .greatestFiniteMagnitude, post: post, success: { image in
finishedRetrievingFullImage(image)
}, onFailure: { _ in
finishedRetrievingFullImage(nil)
})
self.tasks.append(task)
}
/**
If the user exits the Media Editor, cancel all requests
*/
func cancel() {
tasks.forEach { $0.cancel() }
}
}
| gpl-2.0 | b69de4327d9522b7baedd2640574d3e8 | 27.5 | 146 | 0.633528 | 4.794393 | false | false | false | false |
xiandan/diaobaoweibo-swift | XWeibo-swift/Classes/Model/Home/View/Cell/XStatusTopView.swift | 1 | 3805 | //
// XStatusTopView.swift
// XWeibo-swift
//
// Created by Apple on 15/11/3.
// Copyright © 2015年 Apple. All rights reserved.
//
import UIKit
let padding = CGFloat(8)
class XStatusTopView: UIView {
var statues: XStatus? {
didSet{
//用户头像
if let iconUrl = statues?.user?.profile_image_url {
userImageView.x_setImageWithURL(NSURL(string: iconUrl), placeholderImage: UIImage(named: "avatar"))
}
//用户名称
userName.text = statues?.user?.name
//时间
timeLabel.text = statues?.created_at
//来源
sourceLabel.text = statues?.source
//认证图标
verifiedView.image = statues?.user?.verifiedTypeImage
//会员等级
menberView.image = statues?.user?.mbrankImage
}
}
//MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
//MARK: - 设置微博数据
private func setupData() {
}
//MARK: - 准备UI
private func prepareUI() {
addSubview(topLineView)
addSubview(userImageView)
addSubview(userName)
addSubview(timeLabel)
addSubview(sourceLabel)
addSubview(verifiedView)
addSubview(menberView)
//约束
topLineView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: self, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 10))
/// 头像视图
userImageView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: topLineView, size: CGSize(width: 35, height: 35), offset: CGPoint(x: padding, y: padding))
/// 名称
userName.ff_AlignHorizontal(type: ff_AlignType.TopRight, referView: userImageView, size: nil, offset: CGPoint(x: padding, y: 0))
/// 时间
timeLabel.ff_AlignHorizontal(type: ff_AlignType.BottomRight, referView: userImageView, size: nil, offset: CGPoint(x: padding, y: 0))
/// 来源
sourceLabel.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: timeLabel, size: nil, offset: CGPoint(x: padding, y: 0))
/// 会员等级
menberView.ff_AlignHorizontal(type: ff_AlignType.CenterRight, referView: userName, size: CGSize(width: 14, height: 14), offset: CGPoint(x: padding, y: 0))
/// 认证图标
verifiedView.ff_AlignInner(type: ff_AlignType.BottomRight, referView: userImageView, size: CGSize(width: 17, height: 17), offset: CGPoint(x: 8.5, y: 8.5))
}
//MARK: - 懒加载
//顶部分割视图
private lazy var topLineView: UIView = {
let topLineView = UIView()
topLineView.backgroundColor = UIColor(white: 0.9, alpha: 1)
return topLineView
}()
//用户头像
private lazy var userImageView = UIImageView()
//用户名称
private lazy var userName: UILabel = UILabel(fontSize: 9, color: UIColor.darkGrayColor())
//时间
private lazy var timeLabel = UILabel(fontSize: 9, color: UIColor.orangeColor())
//来源
private lazy var sourceLabel = UILabel(fontSize: 9, color: UIColor.lightGrayColor())
//认证图标
private lazy var verifiedView = UIImageView()
//会员等级
private lazy var menberView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
}
| apache-2.0 | 5925201d1223db755a8a00474a509236 | 27.888889 | 171 | 0.577747 | 4.59596 | false | false | false | false |
mathcamp/Carlos | Tests/TwoWayTransformerCompositionTests.swift | 1 | 5383 | import Foundation
import Quick
import Nimble
import Carlos
import PiedPiper
struct ComposedTwoWayTransformerSharedExamplesContext {
static let TransformerToTest = "composedTransformer"
}
class TwoWayTransformerCompositionSharedExamplesConfiguration: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("a composed two-way transformer") {
(sharedExampleContext: SharedExampleContext) in
var composedTransformer: TwoWayTransformationBox<String, Int>!
beforeEach {
composedTransformer = sharedExampleContext()[ComposedTwoWayTransformerSharedExamplesContext.TransformerToTest] as? TwoWayTransformationBox<String, Int>
}
context("when transforming a value") {
var result: Int?
beforeEach {
result = nil
}
context("if the transformation is possible") {
beforeEach {
composedTransformer.transform("12.15").onSuccess { result = $0 }
}
it("should not return nil") {
expect(result).notTo(beNil())
}
it("should return the expected result") {
expect(result).to(equal(12))
}
}
context("if the transformation fails in the first transformer") {
beforeEach {
composedTransformer.transform("hallo world").onSuccess { result = $0 }
}
it("should return nil") {
expect(result).to(beNil())
}
}
context("if the transformation fails in the second transformer") {
beforeEach {
composedTransformer.transform("-13.2").onSuccess { result = $0 }
}
it("should return nil") {
expect(result).to(beNil())
}
}
}
context("when doing the inverse transform") {
var result: String?
beforeEach {
result = nil
}
context("when the transformation is possible") {
beforeEach {
composedTransformer.inverseTransform(31).onSuccess { result = $0 }
}
it("should not return nil") {
expect(result).notTo(beNil())
}
it("should return the expected result") {
expect(result).to(equal("31.0"))
}
}
context("if the transformation fails in the first transformer") {
beforeEach {
composedTransformer.inverseTransform(-4).onSuccess { result = $0 }
}
it("should return nil") {
expect(result).to(beNil())
}
}
context("if the transformation fails in the second transformer") {
beforeEach {
composedTransformer.inverseTransform(105).onSuccess { result = $0 }
}
it("should return nil") {
expect(result).to(beNil())
}
}
}
}
}
}
class TwoWayTransformerCompositionTests: QuickSpec {
override func spec() {
var transformer1: TwoWayTransformationBox<String, Float>!
var transformer2: TwoWayTransformationBox<Float, Int>!
var composedTransformer: TwoWayTransformationBox<String, Int>!
beforeEach {
transformer1 = TwoWayTransformationBox(transform: {
Future(value: Float($0), error: TestError.SimpleError)
}, inverseTransform: {
let result = Promise<String>()
if $0 > 100 {
result.fail(TestError.SimpleError)
} else {
result.succeed("\($0)")
}
return result.future
})
transformer2 = TwoWayTransformationBox(transform: {
let result = Promise<Int>()
if $0 < 0 {
result.fail(TestError.SimpleError)
} else {
result.mimic(Future(value: Int($0), error: TestError.SimpleError))
}
return result.future
}, inverseTransform: {
let result = Promise<Float>()
if $0 < 0 {
result.fail(TestError.SimpleError)
} else {
result.mimic(Future(value: Float($0), error: TestError.SimpleError))
}
return result.future
})
}
describe("Transformer composition using the global function") {
beforeEach {
composedTransformer = compose(transformer1, secondTransformer: transformer2)
}
itBehavesLike("a composed two-way transformer") {
[
ComposedTwoWayTransformerSharedExamplesContext.TransformerToTest: composedTransformer
]
}
}
describe("Transformer composition using the instance function") {
beforeEach {
composedTransformer = transformer1.compose(transformer2)
}
itBehavesLike("a composed two-way transformer") {
[
ComposedTwoWayTransformerSharedExamplesContext.TransformerToTest: composedTransformer
]
}
}
describe("Transformer composition using the operator") {
beforeEach {
composedTransformer = transformer1 >>> transformer2
}
itBehavesLike("a composed two-way transformer") {
[
ComposedTwoWayTransformerSharedExamplesContext.TransformerToTest: composedTransformer
]
}
}
}
} | mit | c48f3b17d927130fa25023be306eb5d7 | 28.745856 | 159 | 0.581089 | 5.660358 | false | true | false | false |
zhiquan911/SwiftChatKit | Pod/Classes/common/AudioPlayerUtils.swift | 1 | 5333 | //
// AudioPlayerUtils.swift
// SwiftChatKit
//
// Created by 麦志泉 on 15/9/28.
// Copyright © 2015年 CocoaPods. All rights reserved.
//
import UIKit
import AVFoundation
@objc protocol AudioPlayerUtilsDelegate {
optional func didAudioPlayerBeginPlay(audioPlayer: AVAudioPlayer)
optional func didAudioPlayerStopPlay(audioPlayer: AVAudioPlayer)
optional func didAudioPlayerPausePlay(audioPlayer: AVAudioPlayer)
}
class AudioPlayerUtils: NSObject {
var player: AVAudioPlayer?
var playingFilePath: String?
weak var delegate: AudioPlayerUtilsDelegate?
typealias AudioPlayCompletion = () -> Void
var completion: AudioPlayCompletion?
convenience init(delegate: AudioPlayerUtilsDelegate) {
self.init()
self.delegate = delegate
}
override init() {
super.init()
self.changeProximityMonitorEnableState(true)
UIDevice.currentDevice().proximityMonitoringEnabled = false
}
/// 全局唯一实例
class var sharedInstance: AudioPlayerUtils {
struct Singleton{
static var predicate:dispatch_once_t = 0
static var instance:AudioPlayerUtils? = nil
}
dispatch_once(&Singleton.predicate,{
Singleton.instance = AudioPlayerUtils()
}
)
return Singleton.instance!
}
/**
根据文件路径播放语音
- parameter filePath: 文件路径
*/
func playAudioWithFile(filePath: String, completion:AudioPlayCompletion? = nil) {
if filePath != "" {
do {
//不随着静音键和屏幕关闭而静音。
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
//上次播放的录音
if self.playingFilePath != nil && filePath == self.playingFilePath! {
self.player?.play()
UIDevice.currentDevice().proximityMonitoringEnabled = true
} else {
//不是上次播放的录音
self.player?.stop()
self.player = nil
let pl: AVAudioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: filePath))
pl.delegate = self
pl.play()
self.player = pl
UIDevice.currentDevice().proximityMonitoringEnabled = true
self.completion = completion
}
self.playingFilePath = filePath
} catch let error as NSError {
NSLog("AudioPlayerUtils error:\(error.description)")
}
}
}
/**
暂停
*/
func pausePlayingAudio() {
self.player?.pause()
}
/**
停止播放
*/
func stopAudio() {
self.playingFilePath = ""
self.player?.stop()
UIDevice.currentDevice().proximityMonitoringEnabled = false
}
/**
播放状态
- returns:
*/
func isPlaying() -> Bool {
return self.player?.playing ?? false
}
/**
近距离传感器
- parameter enable:
*/
func changeProximityMonitorEnableState(enable: Bool) {
UIDevice.currentDevice().proximityMonitoringEnabled = true
if UIDevice.currentDevice().proximityMonitoringEnabled {
if enable {
//添加近距离事件监听,添加前先设置为YES,如果设置完后还是NO的读话,说明当前设备没有近距离传感器
NSNotificationCenter.defaultCenter().addObserver(self, selector: "sensorStateChange:", name: UIDeviceProximityStateDidChangeNotification, object: nil)
} else {
//删除近距离事件监听
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceProximityStateDidChangeNotification, object: nil)
UIDevice.currentDevice().proximityMonitoringEnabled = false
}
}
}
func sensorStateChange(notification: NSNotificationCenter) {
do {
//如果此时手机靠近面部放在耳朵旁,那么声音将通过听筒输出,并将屏幕变暗
if UIDevice.currentDevice().proximityState {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
} else {
try AVAudioSession.sharedInstance().setCategory(
AVAudioSessionCategoryPlayback)
if self.player != nil || !self.player!.playing {
UIDevice.currentDevice().proximityMonitoringEnabled = false
}
//没有播放了,也没有在黑屏状态下,就可以把距离传感器关了
// [[UIDevice currentDevice] setProximityMonitoringEnabled:NO];
}
} catch let error as NSError {
NSLog("AudioPlayerUtils error:\(error.description)")
}
}
}
extension AudioPlayerUtils: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
self.stopAudio()
self.completion?()
}
}
| mit | 98e969790ed6eb352d04833fbfc39db5 | 29.819876 | 166 | 0.586256 | 5.428884 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift | Solutions/SolutionsTests/Hard/Hard_057_Insert_Interval_Test.swift | 4 | 4817 | //
// Hard_057_Insert_Interval_Test.swift
// Solutions
//
// Created by Di Wu on 6/13/15.
// Copyright © 2015 diwu. All rights reserved.
//
import XCTest
class Hard_057_Insert_Interval_Test: XCTestCase {
private static let ProblemName: String = "Hard_057_Insert_Interval"
private static let TimeOutName = ProblemName + Default_Timeout_Suffix
private static let TimeOut = Default_Timeout_Value
func test_001() {
let input0: [[Int]] = [
[1,3],
[6,9]
]
let input1: [Int] = [
2,5
]
let expected: [[Int]] = [
[1,5],
[6,9]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_002() {
let input0: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[12,16]
]
let input1: [Int] = [
4,9
]
let expected: [[Int]] = [
[1,2],
[3,10],
[12,16]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_003() {
let input0: [[Int]] = [
]
let input1: [Int] = [
]
let expected: [[Int]] = [
[]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_004() {
let input0: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[12,16]
]
let input1: [Int] = [
1,16
]
let expected: [[Int]] = [
[1,16]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_005() {
let input0: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[12,16]
]
let input1: [Int] = [
2,15
]
let expected: [[Int]] = [
[1,16]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_006() {
let input0: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[12,16]
]
let input1: [Int] = [
2,17
]
let expected: [[Int]] = [
[1,17]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_007() {
let input0: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[99,100]
]
let input1: [Int] = [
200, 202
]
let expected: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[99,100],
[200,202]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_008() {
let input0: [[Int]] = [
[3,5],
[6,7],
[8,10],
[99,100]
]
let input1: [Int] = [
1,2
]
let expected: [[Int]] = [
[1,2],
[3,5],
[6,7],
[8,10],
[99,100],
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
func test_009() {
let input0: [[Int]] = [
[3,5],
[6,7],
[8,10],
[99,100]
]
let input1: [Int] = [
80,81
]
let expected: [[Int]] = [
[3,5],
[6,7],
[8,10],
[80,81],
[99,100]
]
asyncHelper(input0: input0, input1: input1, expected: expected)
}
private func asyncHelper(input0 input0: [[Int]], input1: [Int], expected: [[Int]]) {
weak var expectation: XCTestExpectation? = self.expectationWithDescription(Hard_057_Insert_Interval_Test.TimeOutName)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let result = Hard_057_Insert_Interval.insert(intervals: input0, newInterval: input1)
assertHelper(result == expected, problemName: Hard_057_Insert_Interval_Test.ProblemName, input: [input0, input1], resultValue: result, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectationsWithTimeout(Hard_057_Insert_Interval_Test.TimeOut) { (error: NSError?) -> Void in
if error != nil {
assertHelper(false, problemName: Hard_057_Insert_Interval_Test.ProblemName, input: [input0, input1], resultValue: Hard_057_Insert_Interval_Test.TimeOutName, expectedValue: expected)
}
}
}
}
| mit | d49a7f1154fd87f5cde5bddc63388499 | 25.905028 | 197 | 0.434801 | 3.673532 | false | true | false | false |
clowwindy/firefox-ios | Client/Frontend/Home/TopSitesPanel.swift | 2 | 11496 | /* 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 UIKit
import Storage
private let ThumbnailIdentifier = "Thumbnail"
private let RowIdentifier = "Row"
private let SeparatorKind = "separator"
private let SeparatorIdentifier = "separator"
private let DefaultImage = "defaultFavicon"
class TopSitesPanel: UIViewController, UICollectionViewDelegate, HomePanel {
weak var homePanelDelegate: HomePanelDelegate?
var publicServerAdView: UIView?
var collection: UICollectionView!
var dataSource: TopSitesDataSource!
let layout = TopSitesLayout()
var profile: Profile! {
didSet {
profile.history.get(nil, complete: { (data) -> Void in
self.dataSource.data = data
self.collection.reloadData()
})
}
}
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
layout.setupForOrientation(toInterfaceOrientation)
collection.setNeedsLayout()
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = TopSitesDataSource(data: Cursor(status: .Failure, msg: "Nothing loaded yet"))
layout.registerClass(TopSitesSeparator.self, forDecorationViewOfKind: SeparatorKind)
collection = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collection.backgroundColor = UIColor.whiteColor()
collection.delegate = self
collection.dataSource = dataSource
collection.registerClass(ThumbnailCell.self, forCellWithReuseIdentifier: ThumbnailIdentifier)
collection.registerClass(TopSitesRow.self, forCellWithReuseIdentifier: RowIdentifier)
collection.keyboardDismissMode = .OnDrag
view.addSubview(collection)
publicServerAdView = Shadowsocks.globalShadowsocks().publicServerAdView()
if let adView = publicServerAdView {
view.addSubview(adView)
adView.snp_makeConstraints { make in
make.top.equalTo(self.view.snp_top)
return
}
collection.snp_makeConstraints { make in
make.top.equalTo(adView.snp_bottom)
make.left.equalTo(self.view)
make.right.equalTo(self.view)
make.bottom.equalTo(self.view)
return
}
} else {
collection.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
}
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let site = dataSource?.data[indexPath.item] as? Site {
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: site.url)!)
}
}
}
class TopSitesLayout: UICollectionViewLayout {
let ToolbarHeight: CGFloat = 44
let StatusBarHeight: CGFloat = 20
let RowHeight: CGFloat = 70
let AspectRatio: CGFloat = 0.7
var numRows: CGFloat = 3
var numCols: CGFloat = 2
var width: CGFloat { return self.collectionView?.frame.width ?? 0 }
var thumbnailWidth: CGFloat { return CGFloat(width / numCols) }
var thumbnailHeight: CGFloat { return thumbnailWidth * AspectRatio }
var count: Int {
if let dataSource = self.collectionView?.dataSource as? TopSitesDataSource {
return dataSource.data.count
}
return 0
}
override init() {
super.init()
setupForOrientation(UIApplication.sharedApplication().statusBarOrientation)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupForOrientation(orientation: UIInterfaceOrientation) {
if orientation.isLandscape {
numRows = 2
numCols = 3
} else {
numRows = 3
numCols = 2
}
}
private func getIndexAtPosition(#y: CGFloat) -> Int {
let thumbnailSectionHeight: CGFloat = thumbnailWidth * numRows
if y < thumbnailSectionHeight {
let row = Int(y / thumbnailHeight)
return min(count - 1, max(0, row * Int(numCols)))
}
return min(count - 1, max(0, Int((y - thumbnailSectionHeight) / RowHeight + numRows * numCols)))
}
override func collectionViewContentSize() -> CGSize {
let c = CGFloat(count)
let offset: CGFloat = ToolbarHeight + StatusBarHeight + HomePanelButtonContainerHeight
if c <= numRows * numCols {
let row = floor(Double(c / numCols))
return CGSize(width: width, height: CGFloat(row) * thumbnailHeight + offset)
}
let h = (c - numRows * numCols) * RowHeight
return CGSize(width: width, height: numRows * thumbnailHeight + h + offset)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
let start = getIndexAtPosition(y: rect.origin.y)
let end = getIndexAtPosition(y: rect.origin.y + rect.height)
var attrs = [UICollectionViewLayoutAttributes]()
if start == -1 || end == -1 {
return attrs
}
for i in start...end {
let indexPath = NSIndexPath(forItem: i, inSection: 0)
let attr = layoutAttributesForItemAtIndexPath(indexPath)
attrs.append(attr)
if CGFloat(i) >= (numRows * numCols) - 1 {
let decoration = layoutAttributesForDecorationViewOfKind(SeparatorKind, atIndexPath: indexPath)
attrs.append(decoration)
}
}
return attrs
}
override func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let decoration = UICollectionViewLayoutAttributes(forDecorationViewOfKind: elementKind, withIndexPath: indexPath)
let h = ((CGFloat(indexPath.item + 1)) - numRows * numCols) * RowHeight
decoration.frame = CGRect(x: 0,
y: CGFloat(thumbnailHeight * numRows + h),
width: width,
height: 1)
return decoration
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attr = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let i = CGFloat(indexPath.item)
if i < numRows * numCols {
let row = floor(Double(i / numCols))
let col = i % numCols
attr.frame = CGRect(x: CGFloat(thumbnailWidth * col),
y: CGFloat(row) * thumbnailHeight,
width: thumbnailWidth,
height: thumbnailHeight)
} else {
let h = CGFloat(i - numRows * numCols) * RowHeight
attr.frame = CGRect(x: 0,
y: CGFloat(thumbnailHeight * numRows + h),
width: width,
height: RowHeight)
}
return attr
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
class TopSitesDataSource: NSObject, UICollectionViewDataSource {
var data: Cursor
init(data: Cursor) {
self.data = data
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let site = data[indexPath.item] as! Site
// Cells for the top site thumbnails.
if indexPath.item < 6 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ThumbnailIdentifier, forIndexPath: indexPath) as! ThumbnailCell
cell.textLabel.text = site.title
if let icon = site.icon {
cell.imageView.sd_setImageWithURL(NSURL(string: icon.url)!)
} else {
cell.imageView.image = UIImage(named: DefaultImage)
}
cell.imageView.contentMode = UIViewContentMode.Center
return cell
}
// Cells for the remainder of the top sites list.
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(RowIdentifier, forIndexPath: indexPath) as! TopSitesRow
cell.textLabel.text = site.title
cell.descriptionLabel.text = site.url
if let icon = site.icon {
cell.imageView.sd_setImageWithURL(NSURL(string: icon.url)!)
} else {
cell.imageView.image = UIImage(named: DefaultImage)
}
return cell
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: SeparatorIdentifier, forIndexPath: indexPath) as! UICollectionReusableView
}
}
private class TopSitesSeparator: UICollectionReusableView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.lightGrayColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// TODO: This should reuse TwoLineCell somehow. Maybe change TwoLineCell to a generic
// UIView, then set it as the contentView so it can be used with any cell type.
private class TopSitesRow: UICollectionViewCell {
let textLabel = UILabel()
let descriptionLabel = UILabel()
let imageView = UIImageView()
let margin = 10
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
contentView.addSubview(descriptionLabel)
contentView.addSubview(imageView)
imageView.contentMode = .ScaleAspectFill
imageView.image = UIImage(named: "defaultFavicon")
imageView.snp_makeConstraints({ make in
make.top.left.equalTo(self.contentView).offset(self.margin)
make.bottom.equalTo(self.contentView).offset(-self.margin)
make.width.equalTo(self.contentView.snp_height).offset(-2*self.margin)
})
textLabel.font = UIFont(name: "FiraSans-SemiBold", size: 13)
textLabel.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor.darkGrayColor()
textLabel.snp_makeConstraints({ make in
make.top.equalTo(self.imageView.snp_top)
make.right.equalTo(self.contentView).offset(-self.margin)
make.left.equalTo(self.imageView.snp_right).offset(self.margin)
})
descriptionLabel.font = UIFont(name: "FiraSans-SemiBold", size: 13)
descriptionLabel.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.lightTextColor() : UIColor.lightGrayColor()
descriptionLabel.snp_makeConstraints({ make in
make.top.equalTo(self.textLabel.snp_bottom)
make.right.equalTo(self.contentView).offset(-self.margin)
make.left.equalTo(self.imageView.snp_right).offset(self.margin)
})
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | de27833ad8f8ec7f72604eed9e6a1fc8 | 37.192691 | 171 | 0.65501 | 5.208881 | false | false | false | false |
stephentyrone/swift | test/IRGen/prespecialized-metadata/struct-inmodule-2argument-4distinct_use.swift | 3 | 11487 | // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
// CHECK: @"$s4main5ValueVys5UInt8VSSGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwCP{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwxx{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwcp{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwca{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwta{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwet{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVys5UInt8VSSGwst{{[^@]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVys5UInt8VSSGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$ss5UInt8VN", %swift.type* @"$sSSN", i32 0, i32 [[ALIGNMENT]], i64 3 }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySSSdGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwCP{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwxx{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwcp{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwca{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwta{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwet{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySSSdGwst{{[^@]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySSSdGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSSN", %swift.type* @"$sSdN", i32 0, i32 16, i64 3 }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySdSiGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[^[:space:]]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_noop_void_return{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySdSiGwet{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVySdSiGwst{{[^@]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVySdSiGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSdN", %swift.type* @"$sSiN", i32 0, i32 8, i64 3 }>, align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVyS2iGWV" = linkonce_odr hidden constant %swift.vwtable {
// CHECK-SAME: i8* bitcast ({{(%swift.opaque\* \(\[[0-9]+ x i8\]\*, \[[0-9]+ x i8\]\*, %swift.type\*\)\* @"\$[a-zA-Z0-9_]+" to i8\*|[^@]+@__swift_memcpy[^[:space:]]* to i8\*)}}),
// CHECK-SAME: i8* bitcast ({{[^@]*}}@__swift_noop_void_return{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@__swift_memcpy{{[^[:space:]]* to i8\*}}),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVyS2iGwet{{[^@]+}} to i8*),
// CHECK-SAME: i8* bitcast ({{[^@]+}}@"$s4main5ValueVyS2iGwst{{[^@]+}} to i8*),
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: [[INT]] {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}},
// CHECK-SAME: i32 {{[0-9]+}}
// CHECK-SAME: },
// NOTE: ignore COMDAT on PE/COFF targets
// CHECK-SAME: align [[ALIGNMENT]]
// CHECK: @"$s4main5ValueVyS2iGMf" = linkonce_odr hidden constant {{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), %swift.type* @"$sSiN", %swift.type* @"$sSiN", i32 0, i32 [[ALIGNMENT]], i64 3 }>, align [[ALIGNMENT]]
struct Value<First, Second> {
let first: First
let second: Second
}
@inline(never)
func consume<T>(_ t: T) {
withExtendedLifetime(t) { t in
}
}
// CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} {
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVyS2iGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySdSiGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySSSdGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys5UInt8VSSGMf" to %swift.full_type*), i32 0, i32 1))
// CHECK: }
func doit() {
consume( Value(first: 13, second: 13) )
consume( Value(first: 13.0, second: 13) )
consume( Value(first: "13.0", second: 13.0) )
consume( Value(first: 13 as UInt8, second: "13.0") )
}
doit()
// CHECK: ; Function Attrs: noinline nounwind readnone
// CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, %swift.type* %1, %swift.type* %2) #{{[0-9]+}} {
// CHECK: entry:
// CHECK: [[ERASED_TYPE_1:%[0-9]+]] = bitcast %swift.type* %1 to i8*
// CHECK: [[ERASED_TYPE_2:%[0-9]+]] = bitcast %swift.type* %2 to i8*
// CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_1]]:
// CHECK: [[EQUAL_TYPE_1_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_1_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_1_1]]
// CHECK: [[EQUAL_TYPE_1_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_1_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_1_1]], [[EQUAL_TYPE_1_2]]
// CHECK: br i1 [[EQUAL_TYPES_1_2]], label %[[EXIT_PRESPECIALIZED_1:[0-9]+]], label %[[TYPE_COMPARISON_2:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_2]]:
// CHECK: [[EQUAL_TYPE_2_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_2_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_2_1]]
// CHECK: [[EQUAL_TYPE_2_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_2_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_2_1]], [[EQUAL_TYPE_2_2]]
// CHECK: br i1 [[EQUAL_TYPES_2_2]], label %[[EXIT_PRESPECIALIZED_2:[0-9]+]], label %[[TYPE_COMPARISON_3:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_3]]:
// CHECK: [[EQUAL_TYPE_3_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_3_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_3_1]]
// CHECK: [[EQUAL_TYPE_3_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSdN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_3_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_3_1]], [[EQUAL_TYPE_3_2]]
// CHECK: br i1 [[EQUAL_TYPES_3_2]], label %[[EXIT_PRESPECIALIZED_3:[0-9]+]], label %[[TYPE_COMPARISON_4:[0-9]+]]
// CHECK: [[TYPE_COMPARISON_4]]:
// CHECK: [[EQUAL_TYPE_4_1:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$ss5UInt8VN" to i8*), [[ERASED_TYPE_1]]
// CHECK: [[EQUAL_TYPES_4_1:%[0-9]+]] = and i1 true, [[EQUAL_TYPE_4_1]]
// CHECK: [[EQUAL_TYPE_4_2:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSSN" to i8*), [[ERASED_TYPE_2]]
// CHECK: [[EQUAL_TYPES_4_2:%[0-9]+]] = and i1 [[EQUAL_TYPES_4_1]], [[EQUAL_TYPE_4_2]]
// CHECK: br i1 [[EQUAL_TYPES_4_2]], label %[[EXIT_PRESPECIALIZED_4:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]]
// CHECK: [[EXIT_PRESPECIALIZED_1]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVyS2iGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_2]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySdSiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_3]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVySSSdGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_PRESPECIALIZED_4]]:
// CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, %swift.type*, i32, i32, i64 }>* @"$s4main5ValueVys5UInt8VSSGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 }
// CHECK: [[EXIT_NORMAL]]:
// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata([[INT]] %0, i8* [[ERASED_TYPE_1]], i8* [[ERASED_TYPE_2]], i8* undef, %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}}
// CHECK: ret %swift.metadata_response {{%[0-9]+}}
// CHECK: }
| apache-2.0 | 3e6922568661a4858a07174e1272c0f0 | 76.09396 | 340 | 0.585357 | 2.968217 | false | false | false | false |
yeziahehe/Gank | Pods/LeanCloud/Sources/Storage/DataType/File.swift | 1 | 6414 | //
// File.swift
// LeanCloud
//
// Created by Tianyong Tang on 2018/9/19.
// Copyright © 2018 LeanCloud. All rights reserved.
//
import Foundation
/**
LeanCloud file type.
*/
public final class LCFile: LCObject {
/// The file URL.
@objc public dynamic var url: LCString?
/**
The file key.
It's the resource key of third-party file hosting provider.
It may be nil for some providers.
*/
@objc public dynamic var key: LCString?
/// The file name.
@objc public dynamic var name: LCString?
/// The file meta data.
@objc public dynamic var metaData: LCDictionary?
/// The file hosting provider.
@objc public dynamic var provider: LCString?
/// The file bucket.
@objc public dynamic var bucket: LCString?
/**
The MIME type of file.
For uploading, you can use this property to explictly set MIME type of file content.
It's an alias of property 'mime_type'.
*/
public var mimeType: LCString? {
get {
return self.get("mime_type") as? LCString
}
set {
try? self.set("mime_type", value: newValue)
}
}
/// The HTTP client.
private lazy var httpClient = HTTPClient.default
public required init() {
super.init()
}
/**
Create file with URL.
- parameter url: The file URL.
*/
public init(url: LCStringConvertible) {
self.url = url.lcString
}
/**
The file payload.
This type represents a resource to be uploaded.
*/
public enum Payload {
/// File content represented by data.
case data(data: Data)
/// File content represented by file URL.
case fileURL(fileURL: URL)
}
/// The payload to be uploaded.
private(set) var payload: Payload?
/**
Create file with content.
- parameter content: The file content.
*/
public init(payload: Payload) {
self.payload = payload
}
public override class func objectClassName() -> String {
return "_File"
}
override public func save() -> LCBooleanResult {
return expect { fulfill in
self.save(
progressInBackground: { _ in /* Nop */ },
completion: { result in
fulfill(result)
})
}
}
override public func save(
_ completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
return save(
progress: { _ in /* Nop */ },
completion: completion)
}
/**
Save current file.
- parameter progress: The progress handler.
- parameter completion: The completion handler.
- returns: The request of saving.
*/
public func save(
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
return save(
progressInBackground: { value in
mainQueueAsync {
progress(value)
}
},
completion: { result in
mainQueueAsync {
completion(result)
}
})
}
/**
Save current file and call handler in background thread.
- parameter progress: The progress handler.
- parameter completion: The completion handler.
- returns: The request of saving.
*/
@discardableResult
private func save(
progressInBackground progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
if let _ = objectId {
let error = LCError(
code: .inconsistency,
reason: "Cannot update file after it has been saved.")
return httpClient.request(error: error) { result in
completion(result)
}
}
if let payload = payload {
return upload(payload: payload, progress: progress, completion: { result in
self.handleUploadResult(result, completion: completion)
})
} else if let _ = url {
let parameters = dictionary.jsonValue as? [String: Any]
return httpClient.request(.post, "files", parameters: parameters) { response in
let result = LCValueResult<LCDictionary>(response: response)
self.handleSaveResult(result, completion: completion)
}
} else {
let error = LCError(code: .notFound, reason: "No payload or URL to upload.")
return httpClient.request(error: error) { result in
completion(result)
}
}
}
/**
Upload payload.
- parameter payload: The payload to be uploaded.
- parameter progress: The progress handler.
- parameter completion: The completion handler.
- returns: The uploading request.
*/
private func upload(
payload: Payload,
progress: @escaping (Double) -> Void,
completion: @escaping (LCBooleanResult) -> Void) -> LCRequest
{
let uploader = FileUploader(file: self, payload: payload)
return uploader.upload(
progress: progress,
completion: completion)
}
/**
Handle result for payload uploading.
If result is successful, it will discard changes.
- parameter result: The save result.
- parameter completion: The completion closure.
*/
private func handleUploadResult(
_ result: LCBooleanResult,
completion: (LCBooleanResult) -> Void)
{
switch result {
case .success:
discardChanges()
case .failure:
break
}
completion(result)
}
/**
Handle result for saving.
If result is successful, it will discard changes.
- parameter result: The save result.
- parameter completion: The completion closure.
*/
private func handleSaveResult(
_ result: LCValueResult<LCDictionary>,
completion: (LCBooleanResult) -> Void)
{
switch result {
case .success(let dictionary):
dictionary.forEach { (key, value) in
update(key, value)
}
discardChanges()
completion(.success)
case .failure(let error):
completion(.failure(error: error))
}
}
}
| gpl-3.0 | 55825b6dbe9fe64eceb1a9210acc1406 | 24.248031 | 91 | 0.572431 | 4.887957 | false | false | false | false |
concurlabs/SwiftyConcur | Source/ConnectionRequests.swift | 1 | 2824 | import Alamofire
import SwiftyJSON
public class ConnectionRequest: ConcurObject {
private(set) public var FirstName: String!
private(set) public var ID: String!
private(set) public var LastModified: String!
private(set) public var LastName: String!
private(set) public var LoyaltyNumber: String!
private(set) public var MiddleName: String!
private(set) public var RequestToken: String!
private(set) public var Status: String!
private(set) public var URI: String!
private init(firstName: String!, id: String!, lastModified: String!, lastName: String!, loyaltyNumber: String!, middleName: String!, requestToken: String!, status: String!, uri: String!) {
self.FirstName = firstName
self.ID = id
self.LastModified = lastModified
self.LastName = lastName
self.LoyaltyNumber = loyaltyNumber
self.MiddleName = middleName
self.RequestToken = requestToken
self.Status = status
self.URI = uri
}
public required convenience init(json: JSON) {
self.init(firstName: json["FirstName"].string, id: json["ID"].string, lastModified: json["LastModified"].string, lastName: json["LastName"].string, loyaltyNumber: json["LoyaltyNumber"].string, middleName: json["MiddleName"].string, requestToken: json["RequestToken"].string, status: json["Status"].string, uri: json["URI"].string)
}
}
public extension ConcurClient {
public func connectionRequestsGet(options: [String : AnyObject?], callback: (_ error: String, _ returnValue: ConcurCollection<ConnectionRequest>) -> Void) {
if let request = ConcurClient.getHTTPRequest(endpoint: "api/v3.0/common/connectionrequests", options: options) {
ConcurClient.sendRequest(request: request, callback: callback)
}
}
public func connectionRequestsPost(options: [String : AnyObject?], callback: (_ error: String, _ returnValue: ConcurCollection<ConnectionRequest>) -> Void) {
if let request = ConcurClient.postHTTPRequest(endpoint: "api/v3.0/common/connectionrequests", options: options) {
ConcurClient.sendRequest(request: request, callback: callback)
}
}
public func connectionRequestsPut(options: [String : AnyObject?], callback: (_ error: String, _ returnValue: ConcurCollection<ConnectionRequest>) -> Void) {
if let request = ConcurClient.putHTTPRequest(endpoint: "api/v3.0/common/connectionrequests", options: options) {
ConcurClient.sendRequest(request: request, callback: callback)
}
}
public func connectionRequestsDelete(options: [String : AnyObject?], callback: (_ error: String, _ returnValue: ConcurCollection<ConnectionRequest>) -> Void) {
if let request = ConcurClient.deleteHTTPRequest(endpoint: "api/v3.0/common/connectionrequests", options: options) {
ConcurClient.sendRequest(request: request, callback: callback)
}
}
}
| apache-2.0 | 0877dd614d3fb9e4016ff641ffb85d20 | 46.066667 | 334 | 0.732649 | 4.358025 | false | false | false | false |
xiaoyouPrince/DYLive | DYLive/DYLive/Classes/Main/Controller/BaceAnchorViewController.swift | 1 | 5375 | //
// BaceAnchorViewController.swift
// DYLive
//
// Created by 渠晓友 on 2017/5/3.
// Copyright © 2017年 xiaoyouPrince. All rights reserved.
//
import UIKit
// MARK: - 定义常量
private let kItemMargin : CGFloat = 10
private let kCycleViewHeight : CGFloat = kScreenW * 3 / 8
private let kGameViewHeight : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
let kItemWidth : CGFloat = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemHeight : CGFloat = kItemWidth * 3 / 4
let kPrettyItemHeight : CGFloat = kItemWidth * 4 / 3
let kPrettyCellID = "kPrettyCellID"
class BaceAnchorViewController: BaceViewController {
// MARK: - 懒加载
var baceVM : BaseViewModel! //定义一个属性,用的时候能直接用
lazy var collectionView : UICollectionView = { [unowned self] in
var layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 10
layout.sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
layout.minimumInteritemSpacing = kItemMargin
layout.itemSize = CGSize(width: kItemWidth, height: kNormalItemHeight)
layout.headerReferenceSize = CGSize(width: kScreenW, height: 50)
let collectionViewY : CGFloat = kStatusBarH + kNavBarH + kTabbarH
let frame = CGRect(x: 0, y:0 , width: kScreenW, height: kScreenH - collectionViewY - kTabbarH)
let collectionView = UICollectionView(frame: frame, collectionViewLayout:layout )
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
// 注册normal类型的cell
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
// 注册组头
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
buildUI()
loadData()
}
}
// MARK: - BuildUI
extension BaceAnchorViewController{
override func buildUI() {
view.addSubview(collectionView)
contentView = collectionView
super.buildUI()
}
}
// MARK: - LoadData
extension BaceAnchorViewController{
@objc
func loadData() {
self.collectionView.reloadData()
}
}
// MARK: - CollectionViewDataSource
extension BaceAnchorViewController : UICollectionViewDataSource
{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.baceVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let anchorGroup = self.baceVM.anchorGroups[section]
return (anchorGroup.anchors.count)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 定义cell
var cell : CollectionBaseCell!
cell = collectionView .dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
let anchorGroup = self.baceVM.anchorGroups[indexPath.section]
cell.anchor = anchorGroup.anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.创建header
let header : CollectionHeaderView = collectionView .dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给header赋值
header.group = self.baceVM.anchorGroups[indexPath.section]
return header
}
}
// MARK: - CollectionViewDelegate
extension BaceAnchorViewController : UICollectionViewDelegate {
// 被点击的方法
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let anchorGroup = self.baceVM.anchorGroups[indexPath.section]
let anchor = anchorGroup.anchors[indexPath.item]
// 根据不同类型的主播进入不同的控制器
// anchor.isVertical == 0 ? showRoomNormalViewController() : showRoomShowViewController()
anchorGroup.tag_name != "星秀" ? showRoomNormalViewController() : showRoomShowViewController()
}
func showRoomShowViewController() {
let roomShow = RoomShowViewController()
self.present(roomShow, animated: true, completion: nil)
}
func showRoomNormalViewController() {
let roomNormal = RoomNormalViewController()
// roomNormal.hidesBottomBarWhenPushed = true
navigationController?.pushViewController(roomNormal, animated: true)
}
}
| mit | c1041a685754297d0bf41c49ea6677ce | 30.566265 | 191 | 0.675382 | 5.610278 | false | false | false | false |
yagiz/Bagel | mac/Bagel/Base/Views/FlatTableHeaderCell.swift | 1 | 1675 | //
// BaseTableHeaderCell.swift
// Bagel
//
// Created by Yagiz Gurgul on 1.10.2018.
// Copyright © 2018 Yagiz Lab. All rights reserved.
//
import Cocoa
import macOSThemeKit
class FlatTableHeaderCell: NSTableHeaderCell {
var titleLeftMargin = CGFloat(5.0)
var titleTopMargin = CGFloat(0.0)
override init(textCell string: String) {
super.init(textCell: string)
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
self.drawInterior(withFrame: cellFrame, in: controlView)
}
override func drawInterior(withFrame cellFrame: NSRect, in controlView: NSView) {
ThemeColor.contentBarColor.setFill()
cellFrame.fill()
let fullRange = NSRange.init(location: 0, length: self.stringValue.count)
let attributedString = NSMutableAttributedString(string: self.stringValue)
attributedString.addAttribute(.foregroundColor, value: NSColor.labelColor, range: fullRange)
attributedString.addAttribute(.font, value: FontManager.mainMediumFont(size: 13), range: fullRange)
self.attributedStringValue = attributedString
super.drawInterior(withFrame: NSRect.init(x: self.titleLeftMargin + cellFrame.origin.x, y: self.titleTopMargin, width: cellFrame.size.width, height: cellFrame.size.height), in: controlView)
}
override func highlight(_ flag: Bool, withFrame cellFrame: NSRect, in controlView: NSView) {
self.drawInterior(withFrame: cellFrame, in: controlView)
}
}
| apache-2.0 | 4a7b3fe06e9e3716519ce03605e69282 | 30.584906 | 197 | 0.676225 | 4.61157 | false | false | false | false |
mozilla-mobile/prox | Prox/Prox/Data/FirebasePlacesDatabase.swift | 1 | 4166 | /* 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 Foundation
import Firebase
import Deferred
import CoreLocation
// Adding "$name/" allows you to develop against a locally run database.
// TODO prox-server – allow this string to be passed in as a URL parameter when in debug mode.
private let ROOT_PATH = AppConstants.firebaseRoot
private let VENUES_PATH = ROOT_PATH + "venues/"
private let GEOFIRE_PATH = VENUES_PATH + "locations/"
private let DETAILS_PATH = VENUES_PATH + "details/"
class FirebasePlacesDatabase: PlacesDatabase {
private let placeDetailsRef: FIRDatabaseReference
private let geofire: GeoFire
init() {
let rootRef = FIRDatabase.database().reference()
placeDetailsRef = rootRef.child(DETAILS_PATH)
geofire = GeoFire(firebaseRef: rootRef.child(GEOFIRE_PATH))
}
/// Queries GeoFire to get the place keys around the given location and
/// then queries Firebase to get the place details for the place keys.
func getPlaces(forLocation location: CLLocation, withRadius radius: Double) -> Future<[DatabaseResult<Place>]> {
let queue = DispatchQueue.global(qos: .userInitiated)
let places = getPlaceKeys(aroundPoint: location, withRadius: radius).andThen(upon: queue) { (placeKeyToLoc) -> Future<[DatabaseResult<Place>]> in
return self.getPlaceDetails(fromKeys: Array(placeKeyToLoc.keys)).allFilled()
}
return places
}
/// Queries GeoFire to find keys that represent locations around the given point.
private func getPlaceKeys(aroundPoint location: CLLocation, withRadius radius: Double) -> Deferred<[String:CLLocation]> {
let deferred = Deferred<[String:CLLocation]>()
var placeKeyToLoc = [String:CLLocation]()
guard let circleQuery = geofire.query(at: location, withRadius: radius) else {
deferred.fill(with: placeKeyToLoc)
return deferred
}
// Append results to return object.
circleQuery.observe(.keyEntered) { (key, location) in
if let unwrappedKey = key, let unwrappedLocation = location {
placeKeyToLoc[unwrappedKey] = unwrappedLocation
}
}
// Handle query completion.
circleQuery.observeReady {
log.debug("geofire places query complete: found \(placeKeyToLoc.count) places")
circleQuery.removeAllObservers()
deferred.fill(with: placeKeyToLoc)
}
return deferred
}
/// Queries Firebase to find the place details from the given keys.
///
/// If you're refactoring, I'd keep this method around - it's useful if we want to
/// optimize to load places on-demand, instead of getting all place details at once.
private func getPlaceDetails(fromKeys placeKeys: [String]) -> [Deferred<DatabaseResult<Place>>] {
let placeDetails = placeKeys.map { placeKey -> Deferred<DatabaseResult<Place>> in
queryChildPlaceDetails(by: placeKey)
}
return placeDetails
}
private func queryChildPlaceDetails(by placeKey: String) -> Deferred<DatabaseResult<Place>> {
let deferred = Deferred<DatabaseResult<Place>>()
let childRef = placeDetailsRef.child(placeKey)
childRef.queryOrderedByKey().observeSingleEvent(of: .value) { (data: FIRDataSnapshot) in
guard data.exists() else {
deferred.fill(with: DatabaseResult.fail(withMessage: "Child place key does not exist: \(placeKey)"))
return
}
if let place = Place(fromFirebaseSnapshot: data) {
deferred.fill(with: DatabaseResult.succeed(value: place))
} else {
deferred.fill(with: DatabaseResult.fail(withMessage: "Snapshot missing required Place data: \(data)"))
}
}
return deferred
}
func getPlace(forKey key: String) -> Deferred<DatabaseResult<Place>> {
return queryChildPlaceDetails(by: key)
}
}
| mpl-2.0 | a1557489ffaab6dd5ccce0b2a302b20a | 40.63 | 153 | 0.67019 | 4.661814 | false | false | false | false |
eldesperado/SpareTimeAlarmApp | SpareTimeMusicApp/CoreDataOperationHelper.swift | 1 | 9459 | //
// CoreDataOperationHelper.swift
// SpareTimeAlarmApp
//
// Created by Pham Nguyen Nhat Trung on 8/6/15.
// Copyright (c) 2015 Pham Nguyen Nhat Trung. All rights reserved.
//
import CoreData
import Foundation
enum EntityTableName: String {
case AlarmRecord = "AlarmRecord"
case RepeatDate = "RepeatDate"
}
struct RecordHelper {
static func getRepeatDatesString(repeatDates: RepeatDate) -> String {
// Get Current Date
let currentDay = DateTimeHelper.getCurrentDate().dayOfWeek
var string = ""
// FIXME: Please fix this ugly code
if repeatDates.isMon.boolValue {
if currentDay == 2 {
string += "Today"
} else {
string += "Mon"
}
}
if repeatDates.isTue.boolValue {
if currentDay == 3 {
string += ", Today"
} else {
string += ", Tue"
}
}
if repeatDates.isWed.boolValue {
if currentDay == 4 {
string += ", Today"
} else {
string += ", Wed"
}
}
if repeatDates.isThu.boolValue {
if currentDay == 5 {
string += ", Today"
} else {
string += ", Thu"
}
}
if repeatDates.isFri.boolValue {
if currentDay == 6 {
string += ", Today"
} else {
string += ", Fri"
}
}
if repeatDates.isSat.boolValue {
if currentDay == 7 {
string += ", Today"
} else {
string += ", Sat"
}
}
if repeatDates.isSun.boolValue {
if currentDay == 8 {
string += ", Today"
} else {
string += ", Sun"
}
}
// Check whether this string is empty or not. If empty, return "No Repeat" string
if string.isEmpty {
return "No Repeat"
}
// Check whether this string begins with " ," characters. If does, remove
if string.hasPrefix(", ") {
string.removeRange(string.startIndex...string.startIndex.advancedBy(1))
}
// Check whether this string contains all dates, that means there are 7 Date strings. If does, return "Everyday"
if countStringsSeparateByColon(string) == 7 {
return "Everyday"
}
return string
}
private static func countStringsSeparateByColon(string: String) -> Int {
let strings = string.characters.split(isSeparator: { $0 == ","}).map { String($0) }
return strings.count
}
static func getAlarmRecordIndexInAlarmArrays(alarmArray: [AlarmRecord], timeStamp: String) -> Int? {
var i = 0
for record in alarmArray {
if record.timeStamp == timeStamp {
return i
}
i++
}
return nil
}
// Convert RepeatDates NSManagedObject to an array containing all activated dates
static func getRepeatDates(alarmRecord: AlarmRecord) -> [Int]? {
let repeatDates = alarmRecord.repeatDates
let dates = NSMutableArray()
if (repeatDates.isSun.boolValue) {
dates.addObject(NumberToDate.Sunday.date)
}
if (repeatDates.isMon.boolValue) {
dates.addObject(NumberToDate.Monday.date)
}
if (repeatDates.isTue.boolValue) {
dates.addObject(NumberToDate.Tuesday.date)
}
if (repeatDates.isWed.boolValue) {
dates.addObject(NumberToDate.Wednesday.date)
}
if (repeatDates.isThu.boolValue) {
dates.addObject(NumberToDate.Thursday.date)
}
if (repeatDates.isFri.boolValue) {
dates.addObject(NumberToDate.Friday.date)
}
if (repeatDates.isSat.boolValue) {
dates.addObject(NumberToDate.Saturday.date)
}
if let array = dates as NSArray as? [Int] {
return array
} else {
return nil
}
}
}
extension CoreDataHelper {
// value of value types for function listAlarmRecords() (read more: https://realm.io/news/andy-matuschak-controlling-complexity/)
struct ListingParameters {
var sortDescriptor: NSSortDescriptor?
var predicateFilter: NSPredicate?
}
// MARK: AlarmRecord Table
// MARK: FETCH: Fetches AlarmRecord table's records
func listAllAlarmRecordsMostRecently() -> [AlarmRecord]? {
// Create option
let sortDescriptor = NSSortDescriptor(key: "alarmTime" , ascending: false)
let options = ListingParameters(sortDescriptor: sortDescriptor, predicateFilter: nil)
return listAlarmRecords(listingParameters: options)
}
func listAllActiveAlarmRecordsMostRecently() -> [AlarmRecord]? {
// Create option
let sortDescriptor = NSSortDescriptor(key: "alarmTime" , ascending: true)
let predicate = NSPredicate(format: "isActive == true")
let options = ListingParameters(sortDescriptor: sortDescriptor, predicateFilter: predicate)
return listAlarmRecords(listingParameters: options)
}
func listAlarmRecords(listingParameters parameters: ListingParameters) -> [AlarmRecord]? {
let fetchReq : NSFetchRequest = NSFetchRequest(entityName: EntityTableName.AlarmRecord.rawValue)
if let predicate = parameters.predicateFilter {
fetchReq.predicate = predicate
}
if let sortDes = parameters.sortDescriptor {
fetchReq.sortDescriptors = [sortDes]
}
fetchReq.returnsObjectsAsFaults = false
let result: [AnyObject]?
do {
result = try managedObjectContext!.executeFetchRequest(fetchReq)
} catch {
result = nil
}
return result as? [AlarmRecord]
}
// MARK: INSERT: Insert AlarmRecord table's records in background
func createTempAlarmRecord() -> AlarmRecord {
let newRecord: AlarmRecord = NSEntityDescription.insertNewObjectForEntityForName(EntityTableName.AlarmRecord.rawValue, inManagedObjectContext: backgroundContext!) as! AlarmRecord
let newRDates: RepeatDate = NSEntityDescription.insertNewObjectForEntityForName(EntityTableName.RepeatDate.rawValue, inManagedObjectContext: backgroundContext!) as! RepeatDate
let val = 0
newRDates.isMon = val
newRDates.isTue = val
newRDates.isWed = val
newRDates.isThu = val
newRDates.isFri = val
newRDates.isSat = val
newRDates.isSun = val
newRDates.ofRecord = newRecord
newRecord.repeatDates = newRDates
// Set TimeStamp as UID
setTimeStamp(newRecord)
return newRecord
}
func insertAlarmRecord(alarmTime: NSNumber, ringtoneType: NSNumber, salutationText: String? = "", isRepeat: Bool, repeatDate: RepeatDate?) {
let newRecord: AlarmRecord = NSEntityDescription.insertNewObjectForEntityForName(EntityTableName.AlarmRecord.rawValue, inManagedObjectContext: backgroundContext!) as! AlarmRecord
newRecord.alarmTime = alarmTime
newRecord.ringtoneType = ringtoneType
if let saluStr = salutationText {
newRecord.salutationText = saluStr
}
newRecord.isRepeat = isRepeat
newRecord.isActive = NSNumber(int: 1)
if repeatDate == nil {
let newRDates: RepeatDate = NSEntityDescription.insertNewObjectForEntityForName(EntityTableName.RepeatDate.rawValue, inManagedObjectContext: backgroundContext!) as! RepeatDate
let val = 1
newRDates.isMon = val
newRDates.isTue = val
newRDates.isWed = val
newRDates.isThu = val
newRDates.isFri = val
newRDates.isSat = val
newRDates.isSun = val
newRDates.ofRecord = newRecord
newRecord.repeatDates = newRDates
}
// Set TimeStamp as UID
setTimeStamp(newRecord)
// Save in background thread
saveContext()
// Create a notification
notificationManager.scheduleNewNotification(newRecord)
}
func updateAlarmRecord(record: AlarmRecord, alarmTime: NSNumber? = nil, ringtoneType: NSNumber? = nil, salutationText: String? = "", isRepeat: Bool? = nil, isActive: Bool? = true, repeatDate: RepeatDate? = nil) {
// Update Alarm Record with new values
if let alTime = alarmTime {
record.alarmTime = alTime
}
if let rType = ringtoneType {
record.ringtoneType = rType
}
if let text = salutationText {
record.salutationText = text
}
if let `repeat` = isRepeat {
record.isRepeat = `repeat`
}
if let active = isActive {
record.isActive = active
}
if let rDates = repeatDate {
record.repeatDates.copyValueFrom(rDates)
}
// Save new alarm
saveContext()
// Create a notification
notificationManager.scheduleNewNotification(record)
}
// MARK: Find object
func findRecordInBackgroundManagedObjectContext(managedObjectId: NSManagedObjectID) -> NSManagedObject {
return findRecord(managedObjectId, managedObjectContext: backgroundContext!)
}
func findRecord(managedObjectId: NSManagedObjectID, managedObjectContext: NSManagedObjectContext) -> NSManagedObject {
let managedObject = managedObjectContext.objectWithID(managedObjectId)
return managedObject
}
// MARK: DELETE: Delete AlarmRecord and RepeatDate in cascade
func deleteAlarmRecord(alarmRecord record: AlarmRecord) {
// Cancel location notifications
notificationManager.cancelLocalNotifications(record)
// Find this object in background managed object context
let managedObject = findRecord(record.objectID, managedObjectContext: backgroundContext!)
backgroundContext!.deleteObject(managedObject)
// Save in background thread
saveContext()
}
// MARK: Helpers
private func setTimeStamp(record: AlarmRecord) {
let now = NSDate()
let time = Int(now.timeIntervalSince1970 * 1000)
record.timeStamp = "\(time)"
}
}
| mit | f802b3d090050fd7c2fcf7eb2cce4e91 | 29.61165 | 214 | 0.674596 | 4.741353 | false | false | false | false |
practicalswift/swift | test/IRGen/class_resilience.swift | 1 | 31577 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/class_resilience.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-%target-runtime -DINT=i%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %t/class_resilience.swift
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd" = hidden global [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience21ResilientGenericChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS:{ (i32|i64), i32, i32 }]] zeroinitializer
// CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC9resilient0H7_struct0G3IntVvpWvd" = hidden global [[INT]] 0,
// CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC9resilient0H7_struct0E3IntVvpWvd" = hidden global [[INT]] 0,
// CHECK: @"$s16class_resilience26ClassWithResilientPropertyCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|20}}
// CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd" = hidden constant [[INT]] {{8|16}}
// CHECK: @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|24}}
// CHECK: [[RESILIENTCHILD_NAME:@.*]] = private constant [15 x i8] c"ResilientChild\00"
// CHECK: @"$s16class_resilience14ResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS]] zeroinitializer
// CHECK: @"$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq" = external{{( dllimport)?}} global %swift.method_descriptor
// CHECK: @"$s16class_resilience14ResilientChildCMn" = {{(protected )?}}{{(dllexport )?}}constant <{{.*}}> <{
// -- flags: class, unique, has vtable, has override table, in-place initialization, has resilient superclass
// CHECK-SAME: <i32 0xE201_0050>
// -- parent:
// CHECK-SAME: @"$s16class_resilienceMXM"
// -- name:
// CHECK-SAME: [15 x i8]* [[RESILIENTCHILD_NAME]]
// -- metadata accessor function:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMa"
// -- field descriptor:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMF"
// -- metadata bounds:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMo"
// -- metadata positive size in words (not used):
// CHECK-SAME: i32 0,
// -- num immediate members:
// CHECK-SAME: i32 4,
// -- num fields:
// CHECK-SAME: i32 1,
// -- field offset vector offset:
// CHECK-SAME: i32 0,
// -- superclass:
// CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn"
// -- singleton metadata initialization cache:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMl"
// -- resilient pattern:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMP"
// -- completion function:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCMr"
// -- number of method overrides:
// CHECK-SAME: i32 2,
// CHECK-SAME: %swift.method_override_descriptor {
// -- base class:
// CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn"
// -- base method:
// CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentC8getValueSiyFTq"
// -- implementation:
// CHECK-SAME: @"$s16class_resilience14ResilientChildC8getValueSiyF"
// CHECK-SAME: }
// CHECK-SAME: %swift.method_override_descriptor {
// -- base class:
// CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCMn"
// -- base method:
// CHECK-SAME: @"{{got.|__imp_}}$s15resilient_class22ResilientOutsideParentCACycfCTq"
// -- implementation:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCACycfC"
// CHECK-SAME: }
// CHECK-SAME: }>
// CHECK: @"$s16class_resilience14ResilientChildCMP" = internal constant <{{.*}}> <{
// -- instantiation function:
// CHECK-SAME: i32 0,
// -- destructor:
// CHECK-SAME: @"$s16class_resilience14ResilientChildCfD"
// -- ivar destroyer:
// CHECK-SAME: i32 0,
// -- flags:
// CHECK-SAME: i32 3,
// -- RO data:
// CHECK-objc-SAME: @_DATA__TtC16class_resilience14ResilientChild
// CHECK-native-SAME: i32 0,
// -- metaclass:
// CHECK-objc-SAME: @"$s16class_resilience14ResilientChildCMm"
// CHECK-native-SAME: i32 0
// CHECK: @"$s16class_resilience17MyResilientParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$s16class_resilience16MyResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 60, i32 2, i32 15 }
// CHECK-SAME-64: { [[INT]] 96, i32 2, i32 12 }
// CHECK: @"$s16class_resilience24MyResilientGenericParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 }
// CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 }
// CHECK: @"$s16class_resilience24MyResilientConcreteChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]]
// CHECK-SAME-32: { [[INT]] 64, i32 2, i32 16 }
// CHECK-SAME-64: { [[INT]] 104, i32 2, i32 13 }
// CHECK: @"$s16class_resilience27ClassWithEmptyThenResilientC5emptyAA0E0VvpWvd" = hidden constant [[INT]] 0,
// CHECK: @"$s16class_resilience27ClassWithResilientThenEmptyC5emptyAA0G0VvpWvd" = hidden constant [[INT]] 0,
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience14ResilientChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvgTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvsTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience21ResilientGenericChildC5fields5Int32VvMTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience17MyResilientParentCACycfCTq" = hidden alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience24MyResilientGenericParentC1tACyxGx_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
// CHECK: @"$s16class_resilience24MyResilientConcreteChildC1xACSi_tcfCTq" = {{(protected )?}}{{(dllexport )?}}alias %swift.method_descriptor, getelementptr inbounds
import resilient_class
import resilient_struct
import resilient_enum
// Concrete class with resilient stored property
public class ClassWithResilientProperty {
public let p: Point
public let s: Size
public let color: Int32
public init(p: Point, s: Size, color: Int32) {
self.p = p
self.s = s
self.color = color
}
}
// Concrete class with non-fixed size stored property
public class ClassWithResilientlySizedProperty {
public let r: Rectangle
public let color: Int32
public init(r: Rectangle, color: Int32) {
self.r = r
self.color = color
}
}
// Concrete class with resilient stored property that
// is fixed-layout inside this resilience domain
public struct MyResilientStruct {
public let x: Int32
}
public class ClassWithMyResilientProperty {
public let r: MyResilientStruct
public let color: Int32
public init(r: MyResilientStruct, color: Int32) {
self.r = r
self.color = color
}
}
// Enums with indirect payloads are fixed-size
public class ClassWithIndirectResilientEnum {
public let s: FunnyShape
public let color: Int32
public init(s: FunnyShape, color: Int32) {
self.s = s
self.color = color
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientChild : ResilientOutsideParent {
public var field: Int32 = 0
public override func getValue() -> Int {
return 1
}
}
// Superclass is resilient, so the number of fields and their
// offsets is not known at compile time
public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> {
public var field: Int32 = 0
}
// Superclass is resilient and has a resilient value type payload,
// but everything is in one module
public class MyResilientParent {
public let s: MyResilientStruct = MyResilientStruct(x: 0)
}
public class MyResilientChild : MyResilientParent {
public let field: Int32 = 0
}
public class MyResilientGenericParent<T> {
public let t: T
public init(t: T) {
self.t = t
}
}
public class MyResilientConcreteChild : MyResilientGenericParent<Int> {
public let x: Int
public init(x: Int) {
self.x = x
super.init(t: x)
}
}
extension ResilientGenericOutsideParent {
public func genericExtensionMethod() -> A.Type {
return A.self
}
}
// rdar://48031465
// Field offsets for empty fields in resilient classes should be initialized
// to their best-known value and made non-constant if that value might
// disagree with the dynamic value.
@_fixed_layout
public struct Empty {}
public class ClassWithEmptyThenResilient {
public let empty: Empty
public let resilient: ResilientInt
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
public class ClassWithResilientThenEmpty {
public let resilient: ResilientInt
public let empty: Empty
public init(empty: Empty, resilient: ResilientInt) {
self.empty = empty
self.resilient = resilient
}
}
// ClassWithResilientProperty.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg"(%T16class_resilience26ClassWithResilientPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientProperty metadata accessor
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience26ClassWithResilientPropertyCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience26ClassWithResilientPropertyCMn" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientlySizedProperty.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg"(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ClassWithResilientlySizedProperty metadata accessor
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMa"(
// CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** getelementptr inbounds ({ %swift.type*, i8* }, { %swift.type*, i8* }* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMl", i32 0, i32 0)
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: [[RESPONSE:%.*]] = call swiftcc %swift.metadata_response @swift_getSingletonMetadata([[INT]] %0, %swift.type_descriptor* bitcast ({{.*}} @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn" to %swift.type_descriptor*))
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[RESPONSE]], 1
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[NEW_METADATA:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 0, %entry ], [ [[STATUS]], %cacheIsNull ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[NEW_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithIndirectResilientEnum.color getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg"(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself)
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientChild.field getter
// CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience14ResilientChildC5fields5Int32Vvg"(%T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s16class_resilience14ResilientChildC5fields5Int32VvpWvd"
// CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[FIELD_VALUE]]
// ResilientGenericChild.field getter
// CHECK-LABEL: define hidden swiftcc i32 @"$s16class_resilience21ResilientGenericChildC5fields5Int32Vvg"(%T16class_resilience21ResilientGenericChildC* swiftself)
// FIXME: we could eliminate the unnecessary isa load by lazily emitting
// metadata sources in EmitPolymorphicParameters
// CHECK: load %swift.type*
// CHECK: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience21ResilientGenericChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}}
// CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]*
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]]
// CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8*
// CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V*
// CHECK: call void @swift_beginAccess
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK-NEXT: call void @swift_endAccess
// CHECK: ret i32 [[RESULT]]
// MyResilientChild.field getter
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$s16class_resilience16MyResilientChildC5fields5Int32Vvg"(%T16class_resilience16MyResilientChildC* swiftself)
// CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0
// CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]]
// CHECK: ret i32 [[RESULT]]
// ResilientGenericOutsideParent.genericExtensionMethod()
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s15resilient_class29ResilientGenericOutsideParentC0B11_resilienceE22genericExtensionMethodxmyF"(%T15resilient_class29ResilientGenericOutsideParentC* swiftself) #0 {
// CHECK: [[ISA_ADDR:%.*]] = bitcast %T15resilient_class29ResilientGenericOutsideParentC* %0 to %swift.type**
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s15resilient_class29ResilientGenericOutsideParentCMo", i32 0, i32 0)
// CHECK-NEXT: [[GENERIC_PARAM_OFFSET:%.*]] = add [[INT]] [[BASE]], 0
// CHECK-NEXT: [[ISA_TMP:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[GENERIC_PARAM_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_TMP]], [[INT]] [[GENERIC_PARAM_OFFSET]]
// CHECK-NEXT: [[GENERIC_PARAM_ADDR:%.*]] = bitcast i8* [[GENERIC_PARAM_TMP]] to %swift.type**
// CHECK-NEXT: [[GENERIC_PARAM:%.*]] = load %swift.type*, %swift.type** [[GENERIC_PARAM_ADDR]]
// CHECK: ret %swift.type* [[GENERIC_PARAM]]
// ClassWithResilientProperty metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience26ClassWithResilientPropertyCMr"(%swift.type*, i8*, i8**)
// CHECK: entry:
// CHECK-NEXT: [[FIELDS:%.*]] = alloca [3 x i8**]
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]*
// CHECK-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}}
// CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [3 x i8**]* [[FIELDS]] to i8*
// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{12|24}}, i8* [[FIELDS_ADDR]])
// CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [3 x i8**], [3 x i8**]* [[FIELDS]], i32 0, i32 0
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63
// CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont
// CHECK: dependency-satisfied:
// -- ClassLayoutFlags = 0x100 (HasStaticVTable)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 3, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null
// CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont
// CHECK: dependency-satisfied1:
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd"
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd"
// CHECK: br label %metadata-dependencies.cont
// CHECK: metadata-dependencies.cont:
// CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientProperty method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience26ClassWithResilientPropertyCMu"(%swift.type*, %swift.method_descriptor*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience26ClassWithResilientPropertyCMn" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ClassWithResilientlySizedProperty metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience33ClassWithResilientlySizedPropertyCMr"(%swift.type*, i8*, i8**)
// CHECK: entry:
// CHECK-NEXT: [[FIELDS:%.*]] = alloca [2 x i8**]
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* %0 to [[INT]]*
// CHECK-NEXT: [[FIELDS_DEST:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_ADDR]], [[INT]] {{10|13}}
// CHECK-NEXT: [[FIELDS_ADDR:%.*]] = bitcast [2 x i8**]* [[FIELDS]] to i8*
// CHECK-NEXT: call void @llvm.lifetime.start.p0i8(i64 {{8|16}}, i8* [[FIELDS_ADDR]])
// CHECK-NEXT: [[FIELDS_PTR:%.*]] = getelementptr inbounds [2 x i8**], [2 x i8**]* [[FIELDS]], i32 0, i32 0
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 319)
// CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[RESULT:%.*]] = icmp ule [[INT]] [[STATUS]], 63
// CHECK-NEXT: br i1 [[RESULT]], label %dependency-satisfied, label %metadata-dependencies.cont
// CHECK: dependency-satisfied:
// -- ClassLayoutFlags = 0x100 (HasStaticVTable)
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 256, [[INT]] 2, i8*** [[FIELDS_PTR]], [[INT]]* [[FIELDS_DEST]])
// CHECK-NEXT: [[INITDEP_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK-NEXT: [[INITDEP_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1
// CHECK-NEXT: [[INITDEP_PRESENT:%.*]] = icmp eq %swift.type* [[INITDEP_METADATA]], null
// CHECK-NEXT: br i1 [[INITDEP_PRESENT]], label %dependency-satisfied1, label %metadata-dependencies.cont
// CHECK: dependency-satisfied1:
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd"
// CHECK-native: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* {{.*}}
// CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$s16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd"
// CHECK: br label %metadata-dependencies.cont
// CHECK: metadata-dependencies.cont:
// CHECK-NEXT: [[PENDING_METADATA:%.*]] = phi %swift.type* [ [[SIZE_METADATA]], %entry ], [ [[INITDEP_METADATA]], %dependency-satisfied ], [ null, %dependency-satisfied1 ]
// CHECK-NEXT: [[NEW_STATUS:%.*]] = phi [[INT]] [ 63, %entry ], [ [[INITDEP_STATUS]], %dependency-satisfied ], [ 0, %dependency-satisfied1 ]
// CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[PENDING_METADATA]], 0
// CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[NEW_STATUS]], 1
// CHECK-NEXT: ret %swift.metadata_response [[T1]]
// ClassWithResilientlySizedProperty method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMu"(%swift.type*, %swift.method_descriptor*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience33ClassWithResilientlySizedPropertyCMn" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ResilientChild metadata initialization function
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience14ResilientChildCMr"(%swift.type*, i8*, i8**)
// Initialize field offset vector...
// CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* %0, [[INT]] 0, [[INT]] 1, i8*** {{.*}}, [[INT]]* {{.*}})
// CHECK: ret %swift.metadata_response
// ResilientChild method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience14ResilientChildCMu"(%swift.type*, %swift.method_descriptor*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience14ResilientChildCMn" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
// ResilientChild.field setter dispatch thunk
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s16class_resilience14ResilientChildC5fields5Int32VvsTj"(i32, %T16class_resilience14ResilientChildC* swiftself)
// CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %1, i32 0, i32 0, i32 0
// CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]]
// CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$s16class_resilience14ResilientChildCMo", i32 0, i32 0)
// CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{8|16}}
// CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8*
// CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[METADATA_OFFSET]]
// CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to void (i32, %T16class_resilience14ResilientChildC*)**
// CHECK-NEXT: [[METHOD:%.*]] = load void (i32, %T16class_resilience14ResilientChildC*)*, void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]]
// CHECK-NEXT: call swiftcc void [[METHOD]](i32 %0, %T16class_resilience14ResilientChildC* swiftself %1)
// CHECK-NEXT: ret void
// ResilientGenericChild metadata initialization function
// CHECK-LABEL: define internal %swift.type* @"$s16class_resilience21ResilientGenericChildCMi"(%swift.type_descriptor*, i8**, i8*)
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8* %2)
// CHECK: ret %swift.type* [[METADATA]]
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s16class_resilience21ResilientGenericChildCMr"
// CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8*, i8**)
// CHECK: call swiftcc %swift.metadata_response @swift_initClassMetadata2(%swift.type* [[METADATA]], [[INT]] 0,
// CHECK: ret %swift.metadata_response
// ResilientGenericChild method lookup function
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i8* @"$s16class_resilience21ResilientGenericChildCMu"(%swift.type*, %swift.method_descriptor*)
// CHECK-NEXT: entry:
// CHECK-NEXT: [[RESULT:%.*]] = call i8* @swift_lookUpClassMethod(%swift.type* %0, %swift.method_descriptor* %1, %swift.type_descriptor* bitcast (<{{.*}}>* @"$s16class_resilience21ResilientGenericChildCMn" to %swift.type_descriptor*))
// CHECK-NEXT: ret i8* [[RESULT]]
// CHECK-NEXT: }
| apache-2.0 | 00e47e806adb51d7e20098b4934dde43 | 53.631488 | 248 | 0.688539 | 3.679445 | false | false | false | false |
Pendla/hybrid-typer | src/HybridTyper/InputManager.swift | 1 | 3634 | import Cocoa
import Carbon
class InputManager {
let keyboardSimulator = KeyboardSimulator()
var wordHelper: WordHelper
private var word: String = ""
init(withDictionaryPath path: String) {
wordHelper = WordHelper(withDictionaryPath: path)
initInputListener()
}
private func initInputListener() {
NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler: handleKeyDown(_:))
}
private func handleKeyDown(_ event: NSEvent) {
getActiveInputPosition()
guard let input = event.characters else {
NSLog("There were no characters in the input")
return
}
if event.keyCode == CGKeyCode(kVK_Delete) {
guard word.characters.count > 0 else {
return
}
NSLog("word before deletion: %@", word)
word.removeSubrange(word.index(before: word.endIndex)..<word.endIndex)
NSLog("word after deletion: %@", word)
} else {
// Append the character just typed as long as the user actually inserting somthing into
// the input. Note that even the potential space that creates a new word is included in the
// word that we replace.
word.append(input)
// If we have a word divier, try to convert and replace the word we just finished
if event.keyCode == CGKeyCode(kVK_Space) {
let modifiedWord = wordHelper.convert(word: word)
NSLog("modified word: %@", modifiedWord)
// Determine if the word should/needs to be replaced and perform replacement if it
// is required by requesting the keyboard simulator to do so.
if wordHelper.shouldReplace(word: word, withWord: modifiedWord) {
NSLog("Replacing word: %@ with new word: %@", word, modifiedWord)
keyboardSimulator.replace(word: word, withWord: modifiedWord)
}
// We had a word separator, thus we are now writing a new word, reset the
// word tracking.
word = ""
}
NSLog("active word: %@", word)
}
}
func getActiveInputPosition() -> Int? {
// swiftlint:disable force_cast
let activeElement = AXUIElementCreateSystemWide()
var focusedApplication: AnyObject?
var error = AXUIElementCopyAttributeValue(activeElement,
kAXFocusedApplicationAttribute as CFString,
&focusedApplication)
guard error == .success else { return nil }
var focusedElement: AnyObject?
error = AXUIElementCopyAttributeValue(focusedApplication as! AXUIElement,
kAXFocusedUIElementAttribute as CFString,
&focusedElement)
guard error == .success else { return nil }
var position: AnyObject?
error = AXUIElementCopyAttributeValue(focusedElement as! AXUIElement,
kAXNumberOfCharactersAttribute as CFString,
&position)
guard error == .success else { return nil }
let pointer = UnsafeMutablePointer<Int>.allocate(capacity: 1)
let success = AXValueGetValue(position as! AXValue, AXValueGetType(position as! AXValue), pointer)
guard success else { return nil }
return pointer.pointee
// swiftlint:enable force_cast
}
}
| mit | c2f6e87688e3189bf4186e3edbe4c1ae | 35.707071 | 106 | 0.578976 | 5.616692 | false | false | false | false |
marty-suzuki/QiitaWithFluxSample | Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift | 1 | 4251 | //
// GitHubSearchRepositoriesViewController.swift
// RxExample
//
// Created by Yoshinori Sano on 9/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UIScrollView {
func isNearBottomEdge(edgeOffset: CGFloat = 20.0) -> Bool {
return self.contentOffset.y + self.frame.size.height + edgeOffset > self.contentSize.height
}
}
class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate {
static let startLoadingOffset: CGFloat = 20.0
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>(
configureCell: { (_, tv, ip, repository: Repository) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = repository.name
cell.detailTextLabel?.text = repository.url.absoluteString
return cell
},
titleForHeaderInSection: { dataSource, sectionIndex in
let section = dataSource[sectionIndex]
return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found"
}
)
override func viewDidLoad() {
super.viewDidLoad()
let tableView: UITableView = self.tableView
let loadNextPageTrigger: (Driver<GitHubSearchRepositoriesState>) -> Driver<()> = { state in
tableView.rx.contentOffset.asDriver()
.withLatestFrom(state)
.flatMap { state in
return tableView.isNearBottomEdge(edgeOffset: 20.0) && !state.shouldLoadNextPage
? Driver.just(())
: Driver.empty()
}
}
let activityIndicator = ActivityIndicator()
let searchBar: UISearchBar = self.searchBar
let state = githubSearchRepositories(
searchText: searchBar.rx.text.orEmpty.changed.asDriver().throttle(0.3),
loadNextPageTrigger: loadNextPageTrigger,
performSearch: { URL in
GitHubSearchRepositoriesAPI.sharedAPI.loadSearchURL(URL)
.trackActivity(activityIndicator)
})
state
.map { $0.isOffline }
.drive(navigationController!.rx.isOffline)
.disposed(by: disposeBag)
state
.map { $0.repositories }
.distinctUntilChanged()
.map { [SectionModel(model: "Repositories", items: $0.value)] }
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx.modelSelected(Repository.self)
.subscribe(onNext: { repository in
UIApplication.shared.openURL(repository.url)
})
.disposed(by: disposeBag)
state
.map { $0.isLimitExceeded }
.distinctUntilChanged()
.filter { $0 }
.drive(onNext: { n in
showAlert("Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting")
})
.disposed(by: disposeBag)
tableView.rx.contentOffset
.subscribe { _ in
if searchBar.isFirstResponder {
_ = searchBar.resignFirstResponder()
}
}
.disposed(by: disposeBag)
// so normal delegate customization can also be used
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
// activity indicator in status bar
// {
activityIndicator
.drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible)
.disposed(by: disposeBag)
// }
}
// MARK: Table view delegate
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
deinit {
// I know, I know, this isn't a good place of truth, but it's no
self.navigationController?.navigationBar.backgroundColor = nil
}
}
| mit | 1a00ff414a0ad50bff62bbf011e80556 | 33.552846 | 177 | 0.608706 | 5.23399 | false | false | false | false |
BeitIssieShapiro/IssieBoard | EducKeyboard/ColorUtility.swift | 2 | 3337 | //
// ColorUtility.swift
// IssieKeyboard
//
// Created by Sasson, Kobi on 3/20/15.
// Copyright (c) 2015 Sasson, Kobi. All rights reserved.
//
import Foundation
import UIKit
extension String {
var floatValue: Float {
return (self as NSString).floatValue
}
var isEmptyOrWhiteSpace : Bool { return self.isEmpty || self.isWhiteSpace }
var isWhiteSpace : Bool { return !self.isEmpty && self.trim().isEmpty }
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
}
extension UIColor {
convenience init(rgba: String) {
let redf = ((rgba as NSString).substring(from: 0) as NSString).substring(to: 6)
let greenf = ((rgba as NSString).substring(from: 7) as NSString).substring(to: 6)
let bluef = ((rgba as NSString).substring(from: 14) as NSString).substring(to: 6)
let alphaf = ((rgba as NSString).substring(from: 21) as NSString).substring(to: 6)
/*let red: CGFloat = CGFloat(NumberFormatter().number(from: redf)!)
let green: CGFloat = CGFloat(NumberFormatter().number(from: greenf)!)
let blue: CGFloat = CGFloat(NumberFormatter().number(from: bluef)!)
let alpha: CGFloat = CGFloat(NumberFormatter().number(from: alphaf)!)*/
let red: CGFloat = CGFloat((redf as NSString).floatValue)
let green: CGFloat = CGFloat((greenf as NSString).floatValue)
let blue: CGFloat = CGFloat((bluef as NSString).floatValue)
let alpha: CGFloat = CGFloat((alphaf as NSString).floatValue)
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 255, "Invalid red component")
assert(green >= 0 && green <= 255, "Invalid green component")
assert(blue >= 0 && blue <= 255, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(netHex:Int) {
self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)
}
convenience init(string: String) {
let array = string.characters.split{$0 == ","}.map { String($0) }
assert(array.count == 4, "Invalid string schema" )
let (r,g,b,a) = (CGFloat(array[0].floatValue),CGFloat(array[1].floatValue),CGFloat( array[2].floatValue), CGFloat(array[3].floatValue))
self.init(red: r, green: g, blue: b, alpha: a)
}
var stringValue:String? {
get{
var r:CGFloat = 0,g:CGFloat = 0,b:CGFloat = 0
var a:CGFloat = 0
if self.getRed(&r, green: &g, blue: &b, alpha: &a){
let colorText = NSString(format: "%4.4f,%4.4f,%4.4f,%4.4f",
Float(r),Float(g),Float(b),Float(a))
return colorText as String
}
return nil
}
}
func invertColor()->UIColor{
var green:CGFloat = 0
var red:CGFloat = 0
var blue:CGFloat = 0
var alpha:CGFloat = 0
let _ = [self.getRed(&red, green: &green, blue: &blue, alpha: &alpha)]
return UIColor(red: 1-red, green: 1-green, blue: 1-blue, alpha: 1.0)
}
}
| apache-2.0 | e405b5e4eaa1826eb982b8b552fb322f | 36.494382 | 143 | 0.589452 | 3.728492 | false | false | false | false |
mattrajca/LearnKit | Playgrounds/PrimaryColors.playground/Contents.swift | 1 | 2135 | //: ## Finding Primary Colors of an Image with K-Means
//: [Visit](http://www.mattrajca.com/2016/03/20/finding-primary-colors-in-images-with-learnkit.html) the companion article.
import Cocoa
import LearnKit
//: We start by loading the image we're going to analyze. The goal is to programatically extract the two primary colors of the image – a dark shade of blue for the sky and tan for the building.
let url = NSBundle.mainBundle().URLForResource("Palace", withExtension: "jpg")!
//: 
//: All data in LearnKit gets imported through matrices represented with `LNKMatrix`. We load the image into a matrix where rows represent pixels and columns represent the R, G, and B channels.
guard let matrix = LNKMatrix(imageAtURL: url, format: .RGB) else {
fatalError("The image cannot be loaded.")
}
//: Now we construct a K-Means classifier that will find the two primary clusters, which will correspond to the two primary colors when working with RGB data.
let classifier = LNKKMeansClassifier(matrix: matrix, implementationType:.Accelerate, optimizationAlgorithm: nil, classes: LNKClasses.withCount(2))
//: Passing in `LNKSizeMax` for the iteration count causes the algorithm to run until convergence. A fixed number of iterations can be passed in here to improve performance, though that's not a problem in this example.
classifier.iterationCount = LNKSizeMax
//: Now we run the algorithm, iteratively finding the key colors.
classifier.train()
//: Once training is complete, we obtain the two primary colors, represented as 3-component vectors containing R, G, and B values.
let color1 = classifier.centroidForClusterAtIndex(0)
let color2 = classifier.centroidForClusterAtIndex(1)
//: To visualize the colors, we convert them into `NSColor` objects.
func NSColorFromRGBVector(vector: LNKVector) -> NSColor {
return NSColor(SRGBRed: CGFloat(vector.data[0]), green: CGFloat(vector.data[1]), blue: CGFloat(vector.data[2]), alpha: 1)
}
let nscolor1 = NSColorFromRGBVector(color1)
let nscolor2 = NSColorFromRGBVector(color2)
//: Sure enough, these are the two primary colors of our image!
| mit | e2baf0176e8d6719fc08ef724b9cb6fa | 46.4 | 218 | 0.772152 | 3.957328 | false | false | false | false |
jovito-royeca/Decktracker | ios/Decktracker/PricingTableViewCell.swift | 1 | 4890 | //
// PricingTableViewCell.swift
// Decktracker
//
// Created by Jovit Royeca on 17/07/2016.
// Copyright © 2016 Jovit Royeca. All rights reserved.
//
import UIKit
import CoreData
import JJJUtils
import MBProgressHUD
class PricingTableViewCell: UITableViewCell {
// MARK: Variables
private var _cardOID: NSManagedObjectID?
var cardOID : NSManagedObjectID? {
get {
return _cardOID
}
set (newValue) {
if (_cardOID != newValue) {
_cardOID = newValue
displayPricing()
}
}
}
// MARK: Outlets
@IBOutlet weak var lowPriceLabel: UILabel!
@IBOutlet weak var midPriceLabel: UILabel!
@IBOutlet weak var highPriceLabel: UILabel!
@IBOutlet weak var foilPriceLabel: UILabel!
// MARK: Overrides
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
lowPriceLabel.adjustsFontSizeToFitWidth = true
lowPriceLabel.sizeToFit()
midPriceLabel.adjustsFontSizeToFitWidth = true
midPriceLabel.sizeToFit()
highPriceLabel.adjustsFontSizeToFitWidth = true
highPriceLabel.sizeToFit()
foilPriceLabel.adjustsFontSizeToFitWidth = true
foilPriceLabel.sizeToFit()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
// MARK: Custom Methods
func displayPricing() {
if let _cardOID = _cardOID {
let card = CoreDataManager.sharedInstance.mainObjectContext.objectWithID(_cardOID) as! Card
if TCGPlayerManager.sharedInstance.needsToFetchTCGPlayerPricing(card) {
let completion = { (cardID: String, error: NSError?) in
performUIUpdatesOnMain {
MBProgressHUD.hideHUDForView(self.contentView, animated: true)
if let _ = error {
self.setNAValues()
} else {
if let pricing = card.pricing {
self.setValues(pricing)
} else {
self.setNAValues()
}
}
}
}
do {
MBProgressHUD.showHUDAddedTo(contentView, animated: true)
try TCGPlayerManager.sharedInstance.hiMidLowPrices(card.cardID!, completion: completion)
} catch {
MBProgressHUD.hideHUDForView(contentView, animated: true)
}
} else {
if let pricing = card.pricing {
self.setValues(pricing)
}
}
} else {
setNAValues()
}
}
func setValues(pricing: TCGPlayerPricing) {
if let lowPrice = pricing.lowPrice {
self.lowPriceLabel.text = "$\(lowPrice.doubleValue)"
self.lowPriceLabel.textColor = UIColor.redColor()
} else {
self.lowPriceLabel.text = "N/A"
self.lowPriceLabel.textColor = UIColor.lightGrayColor()
}
if let midPrice = pricing.midPrice {
self.midPriceLabel.text = "$\(midPrice.doubleValue)"
self.midPriceLabel.textColor = UIColor.blueColor()
} else {
self.midPriceLabel.text = "N/A"
self.midPriceLabel.textColor = UIColor.lightGrayColor()
}
if let highPrice = pricing.highPrice {
self.highPriceLabel.text = "$\(highPrice.doubleValue)"
self.highPriceLabel.textColor = JJJUtil.colorFromHexString("#008000")
} else {
self.highPriceLabel.text = "N/A"
self.highPriceLabel.textColor = UIColor.lightGrayColor()
}
if let foilPrice = pricing.foilPrice {
self.foilPriceLabel.text = "$\(foilPrice.doubleValue)"
self.foilPriceLabel.textColor = JJJUtil.colorFromHexString("#998100")
} else {
self.foilPriceLabel.text = "N/A"
self.foilPriceLabel.textColor = UIColor.lightGrayColor()
}
}
func setNAValues() {
lowPriceLabel.text = "N/A"
lowPriceLabel.textColor = UIColor.lightGrayColor()
midPriceLabel.text = "N/A"
midPriceLabel.textColor = UIColor.lightGrayColor()
highPriceLabel.text = "N/A"
highPriceLabel.textColor = UIColor.lightGrayColor()
foilPriceLabel.text = "N/A"
foilPriceLabel.textColor = UIColor.lightGrayColor()
}
}
| apache-2.0 | f5c671a3c0dd234fd05e0279bbbf4feb | 32.717241 | 108 | 0.55001 | 5.456473 | false | false | false | false |
OrRon/ConfettiView | ConfettiView/Classes/ConfettiView.swift | 1 | 1705 | //
// ConfettiView.swift
// Confetti
//
// Created by Or on 04/10/2016.
// Copyright © 2016 Or. All rights reserved.
//
import UIKit
open class ConfettiView: UIView {
open var isAnimating = true
// MARK: Declarations
var confettiLayers = [ConfettiLayer]()
override open var bounds: CGRect {
didSet {
confettiLayers.forEach { layer in layer.resetBounderies() }
}
}
// MARK: Initializers
override init(frame: CGRect) {
super.init(frame: frame)
addConfetti()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addConfetti()
}
// MARK: Confetti Methods
private func addConfetti() {
self.confettiLayers.append(ConfettiLayer(view: self))
self.confettiLayers.append(ConfettiLayer(view: self, depth: 1.5))
self.confettiLayers.append(ConfettiLayer(view: self, depth: 2))
}
// MARK: Touches
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
}
override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
}
// MARK: Controls
/// Stops the animation of all layers
open func stopAnimating() {
isAnimating = false
confettiLayers.forEach { layer in layer.invalidateTimer() }
}
open func startAnimating() {
guard isAnimating == false else { return }
isAnimating = true
confettiLayers.forEach { layer in layer.setupTimerLoop() }
}
}
| mit | 2cf5bebbae770742a85f97b6d6853ebd | 23.342857 | 85 | 0.603286 | 4.568365 | false | false | false | false |
sunfei/Spring | Spring/LoadingView.swift | 22 | 2945 | // The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// 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 UIKit
public class LoadingView: UIView {
@IBOutlet public weak var indicatorView: SpringView!
override public func awakeFromNib() {
let animation = CABasicAnimation()
animation.keyPath = "transform.rotation.z"
animation.fromValue = degreesToRadians(0)
animation.toValue = degreesToRadians(360)
animation.duration = 0.9
animation.repeatCount = HUGE
indicatorView.layer.addAnimation(animation, forKey: "")
}
class func designCodeLoadingView() -> UIView {
return NSBundle(forClass: self).loadNibNamed("LoadingView", owner: self, options: nil)[0] as! UIView
}
}
public extension UIView {
struct LoadingViewConstants {
static let Tag = 1000
}
public func showLoading() {
if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) {
// If loading view is already found in current view hierachy, do nothing
return
}
let loadingXibView = LoadingView.designCodeLoadingView()
loadingXibView.frame = self.bounds
loadingXibView.tag = LoadingViewConstants.Tag
self.addSubview(loadingXibView)
loadingXibView.alpha = 0
SpringAnimation.spring(0.7, animations: {
loadingXibView.alpha = 1
})
}
public func hideLoading() {
if let loadingXibView = self.viewWithTag(LoadingViewConstants.Tag) {
loadingXibView.alpha = 1
SpringAnimation.springWithCompletion(0.7, animations: {
loadingXibView.alpha = 0
loadingXibView.transform = CGAffineTransformMakeScale(3, 3)
}, completion: { (completed) -> Void in
loadingXibView.removeFromSuperview()
})
}
}
}
| mit | db6ba235076b7f12d51a742577f209b1 | 34.914634 | 108 | 0.686248 | 4.966273 | false | false | false | false |
sallar/lunchify-swift | Lunchify/VenuesTableViewController.swift | 1 | 5336 | //
// VenuesTableViewController.swift
// Lunchify
//
// Created by Sallar Kaboli on 11/22/15.
// Copyright © 2015 Sallar Kaboli. All rights reserved.
//
import UIKit
import CoreLocation
import JGProgressHUD
import UIColor_Hex_Swift
import DZNEmptyDataSet
class VenuesTableViewController: VenueListViewController {
var filteredVenues: [Venue] = []
var resultSearchController: UISearchController?
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var refreshControl: UIRefreshControl!
override func configureView() {
super.configureView()
tableView.estimatedRowHeight = 64.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.separatorColor = UIColor("#F0F0F0")
// Progress
HUD?.textLabel.text = NSLocalizedString("LOADING", comment: "Loading...")
HUD?.show(in: self.navigationController?.view)
// Search bar
definesPresentationContext = true
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.searchBarStyle = .minimal
controller.searchBar.tintColor = UIColor("#C2185B")
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
// Empty State
tableView.emptyDataSetSource = self
tableView.emptyDataSetDelegate = self
}
override func venuesDidLoad(_ venues: Venues) {
self.filteredVenues = self.venues
self.shouldEmptyStateBeShowed = (venues.allVenues.count == 0)
}
override func endRefreshing() {
super.endRefreshing()
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
@IBAction func refreshVenues(_ sender: UIRefreshControl) {
loadVenues()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowVenue" {
if let indexPath = tableView.indexPathForSelectedRow {
let venue = filteredVenues[(indexPath as NSIndexPath).row]
let controller = (segue.destination as! MenuViewController)
controller.venue = venue
controller.location = self.location
controller.date = venuesService.getMenuDate("EEEE")
}
}
}
}
extension VenuesTableViewController:
UITableViewDelegate,
UITableViewDataSource,
DZNEmptyDataSetSource,
DZNEmptyDataSetDelegate,
UISearchResultsUpdating {
// MARK: - Search
func updateSearchResults(for searchController: UISearchController) {
if let searchText = searchController.searchBar.text {
filteredVenues = searchText.isEmpty ? venues : venues.filter({(venue: Venue) -> Bool in
return venue.name!.range(of: searchText, options: .caseInsensitive) != nil
})
tableView.reloadData()
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredVenues.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VenueCell", for: indexPath) as! VenueTableViewCell
let venue = self.filteredVenues[(indexPath as NSIndexPath).row]
// Configure the cell...
cell.venueTitleLabel?.text = venue.name
cell.venueAddressLabel?.text = venue.address
if let location = self.location {
cell.venueDistanceLabel?.text = venue.distanceFromLocation(location)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
// MARK: - Empty View
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: "no-venue")
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
return NSAttributedString(string: NSLocalizedString("NO_VENUES", comment: "No venues"))
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
return NSAttributedString(string: NSLocalizedString("NO_VENUES_DESC", comment: "Will add soon"))
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! {
return NSAttributedString(string: NSLocalizedString("RELOAD", comment: "Reload"))
}
func emptyDataSetDidTapButton(_ scrollView: UIScrollView!) {
HUD?.show(in: self.navigationController?.view)
loadVenues()
}
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView!) -> Bool {
return self.shouldEmptyStateBeShowed
}
}
| mit | 829be1c11ba1a9627db6c57a1ea0489a | 32.765823 | 116 | 0.652484 | 5.557292 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/Homework 10/Homework 10/TwoViewController.swift | 1 | 2841 | //
// TwoViewController.swift
// Homework 10
//
// Created by Ivan Krylov on 10.02.2020.
// Copyright © 2020 Ivan Krylov. All rights reserved.
//
import UIKit
struct Settings {
var section = ""
var nameCell: Array<String> = []
}
class SettingsFabric {
static func settings() -> [Settings] {
return [Settings(section: "One", nameCell: [ "Сотовая связь", "Режим модема"]),
Settings(section: "Two", nameCell: ["Уведомления", "Звуки, тактильные сигналы", "Не беспокоить", "Экранное время"]),
Settings(section: "Three", nameCell: ["Основные", "Пункт управления", "Экран и яркость"])
]
}
}
class TwoViewController: UIViewController {
var settings = SettingsFabric.settings()
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension TwoViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if settings[section].section == "One" {
return 3 + settings[section].nameCell.count
} else {
return settings[section].nameCell.count
}
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return " "
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell") as! CellTableViewCell
if settings[indexPath.section].section == "One" {
switch indexPath.row {
case 0:
cell.nameLabel.text = "Авиарежим"
cell.nameTwoLabel.text = ""
cell.accessoryType = UITableViewCell.AccessoryType.none
cell.switcher.isHidden = false
case 1:
cell.nameLabel.text = "Wi-Fi"
cell.nameTwoLabel.text = "Anvicd-YOTA"
cell.switcher.isHidden = true
case 2:
cell.nameLabel.text = "Bluetooth"
cell.nameTwoLabel.text = "Вкл."
cell.switcher.isHidden = true
default:
cell.nameLabel.text = settings[indexPath.section].nameCell[indexPath.row - 3]
cell.nameTwoLabel.text = ""
cell.switcher.isHidden = true
}
} else {
cell.nameLabel.text = settings[indexPath.section].nameCell[indexPath.row]
cell.nameTwoLabel.text = ""
cell.switcher.isHidden = true
}
return cell
}
}
| apache-2.0 | f6be7febb6cca3381911dfef5f82a9cb | 33.75641 | 132 | 0.595721 | 4.379645 | false | false | false | false |
cpuu/OTT | OTT/Central/PeripheralAdvertisementsOverflowServicesViewController.swift | 1 | 2192 | //
// PeripheralAdvertisementsOverflowServicesViewController.swift
// BlueCap
//
// Created by Troy Stribling on 10/18/15.
// Copyright © 2015 Troy Stribling. All rights reserved.
//
import UIKit
import BlueCapKit
class PeripheralAdvertisementsOverflowServicesViewController: UITableViewController {
weak var peripheral: BCPeripheral?
struct MainStoryboard {
static let peripheralAdvertisementsOverflowServiceCell = "PeripheralAdvertisementsOverflowServiceCell"
}
required init?(coder aDecoder:NSCoder) {
super.init(coder:aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(PeripheralAdvertisementsOverflowServicesViewController.didEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object:nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didEnterBackground() {
self.navigationController?.popToRootViewControllerAnimated(false)
BCLogger.debug()
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView:UITableView) -> Int {
return 1
}
override func tableView(_:UITableView, numberOfRowsInSection section:Int) -> Int {
if let services = self.peripheral?.advertisements?.overflowServiceUUIDs {
return services.count
} else {
return 0;
}
}
override func tableView(tableView:UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.peripheralAdvertisementsOverflowServiceCell, forIndexPath:indexPath)
if let services = self.peripheral?.advertisements?.overflowServiceUUIDs {
let service = services[indexPath.row]
cell.textLabel?.text = service.UUIDString
}
return cell
}
}
| mit | 987a50c96a6c8d19a8ed6ecc3347b40f | 32.19697 | 220 | 0.711547 | 5.970027 | false | false | false | false |
ilg/ElJayKit.swift | Pod/Utilities.swift | 1 | 1706 | //
// Utilities.swift
// ElJayKit
//
// Created by Isaac Greenspan on 12/10/15.
// Copyright © 2015 Isaac Greenspan. All rights reserved.
//
import Alamofire
/// Facilitate generics that Swift doesn't directly allow.
public struct Of<T> {
/// Callback taking a `Result` with the given type as the success type and `API.Error` as the error type.
public typealias callback = (Result<T, API.Error>) -> (Void) // TODO: make error more generic?
}
// Dictionary concatenation operator
func +=<K, V> (inout left: [K: V], right: [K: V]) { for (k, v) in right { left[k] = v } }
// MARK: - throw-unwrapping
enum UnwrapError: ErrorType {
case Nil
}
/**
Unwrap an optional, throwing on `nil`
- parameter value: The optional to unwrap
- throws: `UnwrapError.Nil` when the optional is `nil`
- returns: The unwrapped optional
*/
public func unwrapAndThrowOnNil<T>(value: T?) throws -> T {
guard let value = value else {
throw UnwrapError.Nil
}
return value
}
prefix operator ¿ {}
public prefix func ¿<T>(value: T?) throws -> T {
return try unwrapAndThrowOnNil(value)
}
// MARK: NSDate <-> String conversion
private let dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return dateFormatter
}()
extension NSDate {
func ljk_dateString() -> String {
return dateFormatter.stringFromDate(self)
}
class func ljk_dateFromString(dateString: String) -> NSDate? {
return dateFormatter.dateFromString(dateString)
}
}
| mit | b4c29bc27b3116914591af11df2b0298 | 25.609375 | 109 | 0.678802 | 3.809843 | false | false | false | false |
wuwen1030/ViewControllerTransitionDemo | ViewControllerTransition/ModalTrainsition.swift | 1 | 1848 | //
// ModalTrainsition.swift
// ViewControllerTransition
//
// Created by Ben on 15/7/20.
// Copyright (c) 2015年 X-Team. All rights reserved.
//
import UIKit
enum ModalAnimationType: Int {
case simple
case door
}
class ModalTrainsition: NSObject, UIViewControllerTransitioningDelegate{
var animationType:ModalAnimationType
var presentAnimator:UIViewControllerAnimatedTransitioning
var dismissAnimator:UIViewControllerAnimatedTransitioning
var interactiveDismissAnimator:ModalInteractiveAnimation
init(animationType: ModalAnimationType) {
self.animationType = animationType
if animationType == ModalAnimationType.simple {
presentAnimator = SimplePresentAnimator()
dismissAnimator = SimpleDismissAnimator()
interactiveDismissAnimator = ModalInteractiveAnimation(direction:InteractiveDirection.horizental)
}
else {
presentAnimator = DoorPresentAnimator()
dismissAnimator = DoorDismissAnimator()
interactiveDismissAnimator = ModalInteractiveAnimation(direction:InteractiveDirection.vertical)
}
super.init()
}
func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentAnimator
}
func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return dismissAnimator
}
func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return interactiveDismissAnimator.interacting ? interactiveDismissAnimator : nil
}
}
| mit | 2c3f9c23c5d41fe67ee368836c2369d7 | 35.92 | 217 | 0.751896 | 6.93985 | false | false | false | false |
6ag/BaoKanIOS | BaoKanIOS/Classes/Module/News/View/List/JFNewsOnePicCell.swift | 1 | 1426 | //
// JFNewsOnePicCell.swift
// BaoKanIOS
//
// Created by jianfeng on 16/1/14.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
import YYWebImage
class JFNewsOnePicCell: UITableViewCell {
var postModel: JFArticleListModel? {
didSet {
guard let postModel = postModel else { return }
iconView.image = nil
iconView.setImage(urlString: postModel.titlepic ?? "", placeholderImage: UIImage(named: "placeholder_logo"))
articleTitleLabel.text = postModel.title
timeLabel.text = postModel.newstimeString
commentLabel.text = postModel.plnum
showNumLabel.text = postModel.onclick
}
}
@IBOutlet weak var iconView: UIImageView!
@IBOutlet weak var articleTitleLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var commentLabel: UILabel!
@IBOutlet weak var showNumLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// 离屏渲染 - 异步绘制
layer.drawsAsynchronously = true
// 栅格化 - 异步绘制之后,会生成一张独立的图像,cell在屏幕上滚动的时候,本质滚动的是这张图片
layer.shouldRasterize = true
// 使用栅格化,需要指定分辨率
layer.rasterizationScale = UIScreen.main.scale
}
}
| apache-2.0 | e9dd7ab915783f63b921a9c5d845309a | 28.386364 | 120 | 0.637278 | 4.397959 | false | false | false | false |
HeadBear/flyingfur | Blocks/Blocks/Button.swift | 1 | 1893 | //
// Button.swift
// Blocks
//
// Created by Chris Jarvi on 11/10/15.
// Copyright © 2015 Flying Fur Development. All rights reserved.
//
// code from http://nathandemick.com/programming/tutorial/2014/09/23/buttons-sprite-kit-using-swift.html
import SpriteKit
class Button: SKNode {
var defaultButton: SKSpriteNode
var activeButton: SKSpriteNode
var action: () -> Void
init?(defaultButtonImage: String, activeButtonImage: String, buttonAction:() -> Void) {
defaultButton = SKSpriteNode(imageNamed: defaultButtonImage)
activeButton = SKSpriteNode(imageNamed: activeButtonImage)
activeButton.hidden = true
action = buttonAction
super.init()
userInteractionEnabled = true
addChild(defaultButton)
addChild(activeButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
activeButton.hidden = false
defaultButton.hidden = true
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else {
return
}
let location = touch.locationInNode(self)
if defaultButton.containsPoint(location) {
activeButton.hidden = false
defaultButton.hidden = true
} else {
activeButton.hidden = true
defaultButton.hidden = false
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
guard let touch = touches.first else {
return
}
let location = touch.locationInNode(self)
if defaultButton.containsPoint(location) {
action()
}
}
}
| mit | 9ed0530595b90e55dbbbfe64e09426b0 | 28.107692 | 104 | 0.624207 | 5.045333 | false | false | false | false |
alsfox/ZYJModel | ZYJModel/ZYJModel/FMDBHelper/ZYJFMDB.swift | 1 | 2005 | //
// ZYJFMDB.swift
// ZYJModel
//
// Created by 张亚举 on 16/6/14.
// Copyright © 2016年 张亚举. All rights reserved.
//
import UIKit
let sharedFMDB = ZYJFMDB();
class ZYJFMDB: NSObject {
var queue: FMDatabaseQueue?
static override func initialize() {
let docsdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last
let infoDict = Bundle.main().infoDictionary
let bundleNmae = infoDict?[kCFBundleNameKey as String] as! String
let sqlStr = "\(docsdir!)/\(bundleNmae).sql"
HHLog("\(sqlStr)");
//创建队列
let queue = FMDatabaseQueue(path: sqlStr)
sharedFMDB.queue = queue;
}
/// 执行一个 更新语句
internal static func executeUpdate(_ sql: String) -> Bool {
var updateRes = false
sharedFMDB.queue?.inDatabase({ (db) in
let args : CVaListPointer = getVaList([])
updateRes = (db?.executeUpdate(sql, withVAList: args))!
})
return updateRes
}
/// 一个查询语句
static func executeQuery(sql: String, queryResBlock: (set: FMResultSet) -> ()){
sharedFMDB.queue?.inDatabase({ (db) in
let args : CVaListPointer = getVaList([])
let resultSet = [db?.executeQuery(sql, withVAList: args)]
queryResBlock(set: resultSet[0]!)
})
}
/// 查询出指定表的列
static func executeQueryColumns(table: String) -> NSMutableArray {
let columnsM = NSMutableArray()
let sql = "PRAGMA table_info (\(table));"
self.executeQuery(sql: sql) { (set) in
while set.next() {
let column = set.string(forColumn: "name")!
columnsM.add(column)
}
}
return columnsM.mutableCopy() as! NSMutableArray
}
}
| mit | 0837f8903f6809a1c7d86fd5740f61f5 | 25.189189 | 105 | 0.547472 | 4.592417 | false | false | false | false |
psharanda/LayoutOps | Demos/Demos/NSScanner+Swift.swift | 1 | 4180 | // NSScanner+Swift.swift
// A set of Swift-idiomatic methods for NSScanner
//
// (c) 2015 Nate Cook, licensed under the MIT license
import Foundation
extension Scanner {
// MARK: Strings
/// Returns a string, scanned as long as characters from a given character set are encountered, or `nil` if none are found.
func scanCharactersFromSet(_ set: CharacterSet) -> String? {
var value: NSString? = ""
if scanCharacters(from: set, into: &value) {
return value as String?
}
return nil
}
/// Returns a string, scanned until a character from a given character set are encountered, or the remainder of the scanner's string. Returns `nil` if the scanner is already `atEnd`.
func scanUpToCharactersFromSet(_ set: CharacterSet) -> String? {
var value: NSString? = ""
if scanUpToCharacters(from: set, into: &value) {
return value as String?
}
return nil
}
/// Returns the given string if scanned, or `nil` if not found.
func scanString(_ str: String) -> String? {
var value: NSString? = ""
if scanString(str, into: &value) {
return value as String?
}
return nil
}
/// Returns a string, scanned until the given string is found, or the remainder of the scanner's string. Returns `nil` if the scanner is already `atEnd`.
func scanUpToString(_ str: String) -> String? {
var value: NSString? = ""
if scanUpTo(str, into: &value) {
return value as String?
}
return nil
}
// MARK: Numbers
/// Returns a Double if scanned, or `nil` if not found.
func scanDouble() -> Double? {
var value = 0.0
if scanDouble(&value) {
return value
}
return nil
}
/// Returns a Float if scanned, or `nil` if not found.
func scanFloat() -> Float? {
var value: Float = 0.0
if scanFloat(&value) {
return value
}
return nil
}
/// Returns an Int if scanned, or `nil` if not found.
func scanInteger() -> Int? {
var value = 0
if self.scanInt(&value) {
return value
}
return nil
}
/// Returns an Int32 if scanned, or `nil` if not found.
func scanInt() -> Int32? {
var value: Int32 = 0
if scanInt32(&value) {
return value
}
return nil
}
/// Returns an Int64 if scanned, or `nil` if not found.
func scanLongLong() -> Int64? {
var value: Int64 = 0
if scanInt64(&value) {
return value
}
return nil
}
/// Returns a UInt64 if scanned, or `nil` if not found.
func scanUnsignedLongLong() -> UInt64? {
var value: UInt64 = 0
if scanUnsignedLongLong(&value) {
return value
}
return nil
}
/// Returns an NSDecimal if scanned, or `nil` if not found.
func scanDecimal() -> Decimal? {
var value = Decimal()
if scanDecimal(&value) {
return value
}
return nil
}
// MARK: Hex Numbers
/// Returns a Double if scanned in hexadecimal, or `nil` if not found.
func scanHexDouble() -> Double? {
var value = 0.0
if scanHexDouble(&value) {
return value
}
return nil
}
/// Returns a Float if scanned in hexadecimal, or `nil` if not found.
func scanHexFloat() -> Float? {
var value: Float = 0.0
if scanHexFloat(&value) {
return value
}
return nil
}
/// Returns a UInt32 if scanned in hexadecimal, or `nil` if not found.
func scanHexInt() -> UInt32? {
var value: UInt32 = 0
if scanHexInt32(&value) {
return value
}
return nil
}
/// Returns a UInt64 if scanned in hexadecimal, or `nil` if not found.
func scanHexLongLong() -> UInt64? {
var value: UInt64 = 0
if scanHexInt64(&value) {
return value
}
return nil
}
}
| mit | f13c14b1dadb63fc9d0ce4e93c8941b0 | 26.866667 | 186 | 0.546651 | 4.50431 | false | false | false | false |
googlemaps/last-mile-fleet-solution-samples | ios_driverapp_samples/LMFSDriverSampleApp/MapTab/MapStopDetails/StopDetailsPage.swift | 1 | 1980 | /*
* Copyright 2022 Google LLC. All rights reserved.
*
* 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 GoogleMaps
import SwiftUI
/// This view defines the page we push to when the user taps on the
/// Details button for a stop in the map view.
struct StopDetailsPage: View {
@EnvironmentObject var modelData: ModelData
var stop: ModelData.Stop
@State var markers: [GMSMarker]
@State private var zoom: Float = 15
var body: some View {
VStack {
MapViewControllerBridge(
markers: $markers,
selectedMarker: .constant(nil),
zoom: $zoom
)
.frame(height: 250)
ForEach(modelData.tasks(stop: stop)) { task in
StopDetailsPageTask(stop: stop, task: task)
}
.padding()
Spacer()
}
.navigationTitle(stop.stopInfo.plannedWaypoint.description)
.navigationBarTitleDisplayMode(.inline)
}
init(stop: ModelData.Stop) {
// Ensure Google Maps SDK is initialized.
let _ = LMFSDriverSampleApp.googleMapsInited
self.stop = stop
self.markers =
stop.tasks.map({ CustomMarker.makeMarker(task: $0) }) + [
CustomMarker.makeMarker(stop: stop, showLabel: false)
]
}
}
struct StopDetailsPage_Previews: PreviewProvider {
static var previews: some View {
let _ = LMFSDriverSampleApp.googleMapsInited
let modelData = ModelData(filename: "test_manifest")
StopDetailsPage(stop: modelData.stops[0])
.environmentObject(modelData)
}
}
| apache-2.0 | e6a8c8732c3230b209eaaa8701f8c575 | 29.461538 | 91 | 0.697475 | 4.150943 | false | false | false | false |
wokalski/Diff.swift | Sources/Diff+UIKit.swift | 1 | 24274 | #if !os(macOS) && !os(watchOS)
import UIKit
public struct BatchUpdate {
public let deletions: [IndexPath]
public let insertions: [IndexPath]
public let moves: [(from: IndexPath, to: IndexPath)]
public init(
diff: ExtendedDiff,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) {
deletions = diff.flatMap { element -> IndexPath? in
switch element {
case .delete(let at):
return indexPathTransform(IndexPath(row: at, section: 0))
default: return nil
}
}
insertions = diff.flatMap { element -> IndexPath? in
switch element {
case .insert(let at):
return indexPathTransform(IndexPath(row: at, section: 0))
default: return nil
}
}
moves = diff.flatMap { element -> (IndexPath, IndexPath)? in
switch element {
case let .move(from, to):
return (indexPathTransform(IndexPath(row: from, section: 0)), indexPathTransform(IndexPath(row: to, section: 0)))
default: return nil
}
}
}
}
struct NestedBatchUpdate {
let itemDeletions: [IndexPath]
let itemInsertions: [IndexPath]
let itemMoves: [(from: IndexPath, to: IndexPath)]
let sectionDeletions: IndexSet
let sectionInsertions: IndexSet
let sectionMoves: [(from: Int, to: Int)]
init(
diff: NestedExtendedDiff,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
) {
var itemDeletions: [IndexPath] = []
var itemInsertions: [IndexPath] = []
var itemMoves: [(IndexPath, IndexPath)] = []
var sectionDeletions: IndexSet = []
var sectionInsertions: IndexSet = []
var sectionMoves: [(from: Int, to: Int)] = []
diff.forEach { element in
switch element {
case let .deleteElement(at, section):
itemDeletions.append(indexPathTransform(IndexPath(item: at, section: section)))
case let .insertElement(at, section):
itemInsertions.append(indexPathTransform(IndexPath(item: at, section: section)))
case let .moveElement(from, to):
itemMoves.append((indexPathTransform(IndexPath(item: from.item, section: from.section)), indexPathTransform(IndexPath(item: to.item, section: to.section))))
case let .deleteSection(at):
sectionDeletions.insert(sectionTransform(at))
case let .insertSection(at):
sectionInsertions.insert(sectionTransform(at))
case let .moveSection(move):
sectionMoves.append((sectionTransform(move.from), sectionTransform(move.to)))
}
}
self.itemInsertions = itemInsertions
self.itemDeletions = itemDeletions
self.itemMoves = itemMoves
self.sectionMoves = sectionMoves
self.sectionInsertions = sectionInsertions
self.sectionDeletions = sectionDeletions
}
}
public extension UITableView {
/// Animates rows which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
public func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) where T.Iterator.Element: Equatable {
apply(
oldData.extendedDiff(newData),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation,
indexPathTransform: indexPathTransform
)
}
/// Animates rows which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter isEqual: A function comparing two elements of `T`
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
public func animateRowChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqual: (EqualityChecker<T>),
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) {
apply(
oldData.extendedDiff(newData, isEqual: isEqual),
deletionAnimation: deletionAnimation,
insertionAnimation: insertionAnimation,
indexPathTransform: indexPathTransform
)
}
public func apply(
_ diff: ExtendedDiff,
deletionAnimation: UITableViewRowAnimation = .automatic,
insertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 }
) {
let update = BatchUpdate(diff: diff, indexPathTransform: indexPathTransform)
beginUpdates()
deleteRows(at: update.deletions, with: deletionAnimation)
insertRows(at: update.insertions, with: insertionAnimation)
update.moves.forEach { moveRow(at: $0.from, to: $0.to) }
endUpdates()
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(to: newData),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`) /// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualElement: (NestedElementEqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualSection: (EqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Iterator.Element: Collection,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
/// Animates rows and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UITableView`
/// - parameter newData: Data which reflects the current state of `UITableView`
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateRowAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
// https://twitter.com/dgregor79/status/570068545561735169
isEqualElement: (NestedElementEqualityChecker<T>),
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath = { $0 },
sectionTransform: (Int) -> Int = { $0 }
)
where T.Iterator.Element: Collection {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
rowDeletionAnimation: rowDeletionAnimation,
rowInsertionAnimation: rowInsertionAnimation,
sectionDeletionAnimation: sectionDeletionAnimation,
sectionInsertionAnimation: sectionInsertionAnimation,
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform
)
}
public func apply(
_ diff: NestedExtendedDiff,
rowDeletionAnimation: UITableViewRowAnimation = .automatic,
rowInsertionAnimation: UITableViewRowAnimation = .automatic,
sectionDeletionAnimation: UITableViewRowAnimation = .automatic,
sectionInsertionAnimation: UITableViewRowAnimation = .automatic,
indexPathTransform: (IndexPath) -> IndexPath,
sectionTransform: (Int) -> Int
) {
let update = NestedBatchUpdate(diff: diff, indexPathTransform: indexPathTransform, sectionTransform: sectionTransform)
beginUpdates()
deleteRows(at: update.itemDeletions, with: rowDeletionAnimation)
insertRows(at: update.itemInsertions, with: rowInsertionAnimation)
update.itemMoves.forEach { moveRow(at: $0.from, to: $0.to) }
deleteSections(update.sectionDeletions, with: sectionDeletionAnimation)
insertSections(update.sectionInsertions, with: sectionInsertionAnimation)
update.sectionMoves.forEach { moveSection($0.from, toSection: $0.to) }
endUpdates()
}
}
public extension UICollectionView {
/// Animates items which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
public func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
completion: ((Bool) -> Void)? = nil
) where T.Iterator.Element: Equatable {
let diff = oldData.extendedDiff(newData)
apply(diff, completion: completion, indexPathTransform: indexPathTransform)
}
/// Animates items which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter isEqual: A function comparing two elements of `T`
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
public func animateItemChanges<T: Collection>(
oldData: T,
newData: T,
isEqual: EqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
completion: ((Bool) -> Swift.Void)? = nil
) {
let diff = oldData.extendedDiff(newData, isEqual: isEqual)
apply(diff, completion: completion, indexPathTransform: indexPathTransform)
}
public func apply(
_ diff: ExtendedDiff,
completion: ((Bool) -> Swift.Void)? = nil,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 }
) {
performBatchUpdates({
let update = BatchUpdate(diff: diff, indexPathTransform: indexPathTransform)
self.deleteItems(at: update.deletions)
self.insertItems(at: update.insertions)
update.moves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(to: newData),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualElement: NestedElementEqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualElement: isEqualElement
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection,
T.Iterator.Element.Iterator.Element: Equatable {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
completion: completion
)
}
/// Animates items and sections which changed between oldData and newData.
///
/// - parameter oldData: Data which reflects the previous state of `UICollectionView`
/// - parameter newData: Data which reflects the current state of `UICollectionView`
/// - parameter isEqualSection: A function comparing two sections (elements of `T`)
/// - parameter isEqualElement: A function comparing two items (elements of `T.Iterator.Element`)
/// - parameter deletionAnimation: Animation type for deletions
/// - parameter insertionAnimation: Animation type for insertions
/// - parameter indexPathTransform: Closure which transforms zero-based `IndexPath` to desired `IndexPath`
/// - parameter sectionTransform: Closure which transforms zero-based section(`Int`) into desired section(`Int`)
public func animateItemAndSectionChanges<T: Collection>(
oldData: T,
newData: T,
isEqualSection: EqualityChecker<T>,
isEqualElement: NestedElementEqualityChecker<T>,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
completion: ((Bool) -> Swift.Void)? = nil
)
where T.Iterator.Element: Collection {
apply(
oldData.nestedExtendedDiff(
to: newData,
isEqualSection: isEqualSection,
isEqualElement: isEqualElement
),
indexPathTransform: indexPathTransform,
sectionTransform: sectionTransform,
completion: completion
)
}
public func apply(
_ diff: NestedExtendedDiff,
indexPathTransform: @escaping (IndexPath) -> IndexPath = { $0 },
sectionTransform: @escaping (Int) -> Int = { $0 },
completion: ((Bool) -> Void)? = nil
) {
performBatchUpdates({
let update = NestedBatchUpdate(diff: diff, indexPathTransform: indexPathTransform, sectionTransform: sectionTransform)
self.insertSections(update.sectionInsertions)
self.deleteSections(update.sectionDeletions)
update.sectionMoves.forEach { self.moveSection($0.from, toSection: $0.to) }
self.deleteItems(at: update.itemDeletions)
self.insertItems(at: update.itemInsertions)
update.itemMoves.forEach { self.moveItem(at: $0.from, to: $0.to) }
}, completion: completion)
}
}
#endif
| mit | 13dc60c692494419071d4bd5d9ceb9f3 | 47.742972 | 173 | 0.643404 | 5.680786 | false | false | false | false |
ja-mes/experiments | iOS/Tip app/Tip app/TipCalc.swift | 1 | 1009 | //
// TipCalc.swift
// Tip app
//
// Created by James Brown on 8/11/16.
// Copyright © 2016 James Brown. All rights reserved.
//
import Foundation
class TipCalc {
private var _billAmount = 0.0
private var _tipPercent = 0.0
private var _tipAmount = 0.0
private var _totalAmount = 0.0
var billAmount: Double {
get {
return _billAmount
} set {
_billAmount = newValue
}
}
var tipPercent: Double {
get {
return _tipPercent
} set {
_tipPercent = newValue
}
}
var tipAmount: Double {
return _tipAmount
}
var totalAmount: Double {
return _totalAmount
}
init(billAmount: Double, tipPercent: Double) {
self._billAmount = billAmount
self.tipPercent = tipPercent
}
func calculateTip() {
_tipAmount = billAmount * tipPercent
_totalAmount = tipAmount + billAmount
}
}
| mit | 8336101236452581fbc2b5ad749c6eb6 | 18.384615 | 54 | 0.542659 | 4.60274 | false | false | false | false |
gaurav1981/HackingWithSwift | project2/Project2/ViewController.swift | 20 | 1635 | //
// ViewController.swift
// Project2
//
// Created by Hudzilla on 19/11/2014.
// Copyright (c) 2014 Hudzilla. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var button1: UIButton!
@IBOutlet weak var button2: UIButton!
@IBOutlet weak var button3: UIButton!
var countries = [String]()
var correctAnswer = 0
var score = 0
override func viewDidLoad() {
super.viewDidLoad()
countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"]
button1.layer.borderWidth = 1
button2.layer.borderWidth = 1
button3.layer.borderWidth = 1
askQuestion(nil)
}
func askQuestion(action: UIAlertAction!) {
countries.shuffle()
button1.setImage(UIImage(named: countries[0]), forState: .Normal)
button2.setImage(UIImage(named: countries[1]), forState: .Normal)
button3.setImage(UIImage(named: countries[2]), forState: .Normal)
correctAnswer = Int(arc4random_uniform(3))
title = countries[correctAnswer].uppercaseString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func buttonTapped(sender: UIButton) {
var title: String
if sender.tag == correctAnswer {
title = "Correct"
++score
} else {
title = "Wrong"
--score
}
let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion))
presentViewController(ac, animated: true, completion: nil)
}
}
| unlicense | 8ff4040694f93a148265404c0be4b46d | 23.772727 | 129 | 0.706422 | 3.523707 | false | false | false | false |
remirobert/Dotzu-Objective-c | Pods/Dotzu/Dotzu/LogLevelFilter.swift | 2 | 1375 | //
// LogFilter.swift
// exampleWindow
//
// Created by Remi Robert on 22/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class LogLevelFilter {
static let shared = LogLevelFilter()
var enabled: [LogLevel] {
return [error ? .error : nil,
warning ? .warning : nil,
info ? .info : nil,
verbose ? .verbose : nil].flatMap {$0}
}
var error: Bool {
didSet {
setFilter(value: error, key: "errorDisplayed")
}
}
var warning: Bool {
didSet {
setFilter(value: warning, key: "warningDisplayed")
}
}
var info: Bool {
didSet {
setFilter(value: info, key: "infoDisplayed")
}
}
var verbose: Bool {
didSet {
setFilter(value: verbose, key: "verboseDisplayed")
}
}
private func setFilter(value: Bool, key: String) {
UserDefaults.standard.set(value, forKey: key)
LogNotificationApp.refreshLogs.post(Void())
}
init() {
error = UserDefaults.standard.bool2(forKey: "errorDisplayed")
warning = UserDefaults.standard.bool2(forKey: "warningDisplayed")
info = UserDefaults.standard.bool2(forKey: "infoDisplayed")
verbose = UserDefaults.standard.bool2(forKey: "verboseDisplayed")
}
}
| mit | 3f0726c9bf2af2f955d42a1cad3ec04b | 24.444444 | 73 | 0.576419 | 4.189024 | false | false | false | false |
scottsievert/swix | swix_ios_app/swix_ios_app/swix/machine_learning/machine_learning.swift | 8 | 2980 | //
// svm.swift
// swix
//
// Created by Scott Sievert on 7/16/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
class SVM {
// swift --> objc --> objc++ --> c++
var cvsvm:cvSVM;
var svm_type:String
var kernel_type:String
var N:Int
var M:Int
init(){
self.cvsvm = cvSVM()
self.N = -1
self.M = -1
// with linear svc results, we closely match (and do slightly better than) sk-learn
self.svm_type = "C_SVC"
self.kernel_type = "LINEAR"
setParams(svm_type, kernel_type:kernel_type)
}
func setParams(svm_type:String, kernel_type:String, nu:Float=0.5){
// kernel: LINEAR, SIGMOID
// svm_type: C_SVC, ONE_CLASS, NU_SVC, NU_SVR
// careful: NU_SVR and SIGMOID throws an exception error
self.cvsvm.setParams(svm_type.nsstring as String, kernel:kernel_type.nsstring as String, nu:nu.cfloat)
}
func train(responses: matrix, _ targets: ndarray){
// convert matrix2d to NSArray
self.M = responses.shape.0
self.N = responses.shape.1
self.cvsvm.train(!responses, targets:!targets, m:self.M.cint, n:self.N.cint)
}
func predict(response: ndarray) -> Double{
assert(self.N == response.count, "Sizes of input arguments do not match: predict.count != trained.count. The varianbles you're trying to predict a result from must match variables you trained off of.")
let tp = self.cvsvm.predict(!response, n:self.N.cint)
return tp.double
}
func predict(responses: matrix) -> ndarray{
let y = zeros(responses.shape.0)
assert(self.N == responses.shape.1, "Sizes must match")
self.cvsvm.predict(!responses, into:!y, m:responses.shape.0.cint, n:responses.shape.1.cint);
return y
}
}
class kNearestNeighbors{
// finds the nearest neighbor over all points. if want to change, dive into knn.mm and change `int k = cvknn.get_max_k();` in `predict(...)`
var T:Double
var knn:kNN;
var N:Int; // variables
var M:Int; // responses
init(){
assert(false, "Careful! My simple tests failed but it looks like it should work.")
self.T = 1
self.knn = kNN()
self.N = -1
self.M = -1
}
func train(responses: matrix, targets: ndarray){
self.M = responses.shape.0
self.N = responses.shape.1
self.knn.train(!responses, targets: !targets, m:self.M.cint, n:self.N.cint)
}
func predict(x: ndarray, k: Int) -> Double{
assert(self.N == x.count, "Sizes of input arguments do not match: predict.count != trained.count. The varianbles you're trying to predict a result from must match variables you trained off of.")
assert(k <= 32, "k <= 32 for performance reasons enforced by OpenCV.")
let result = self.knn.predict(!x, n:x.n.cint, k:k.cint)
return result.double;
}
}
| mit | 664c959212fc22488fb55f99965d1ead | 35.341463 | 209 | 0.612081 | 3.481308 | false | false | false | false |
lorentey/swift | test/Constraints/diagnostics.swift | 1 | 63720 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
// expected-note@-1 {{required by global function 'f5' where 'T' = '(Int) -> Int'}}
// expected-note@-2 {{required by global function 'f5' where 'T' = '(Int, String)'}}
// expected-note@-3 {{required by global function 'f5' where 'T' = 'Int.Type'}}
// expected-note@-4 {{where 'T' = 'Int'}}
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i, // expected-error@:7 {{cannot convert value of type 'Int' to expected argument type 'Float'}}
i) // expected-error{{extra argument in call}}
// Cannot conform to protocols.
f5(f4) // expected-error {{type '(Int) -> Int' cannot conform to 'P2'; only struct/enum/class types can conform to protocols}}
f5((1, "hello")) // expected-error {{type '(Int, String)' cannot conform to 'P2'; only struct/enum/class types can conform to protocols}}
f5(Int.self) // expected-error {{type 'Int.Type' cannot conform to 'P2'; only struct/enum/class types can conform to protocols}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.missingMember() // expected-error{{value of type 'Int' has no member 'missingMember'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } // expected-note {{where 'T' = 'Int'}}
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{instance method 'wibble' requires that 'Int' conform to 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{for-in loop requires 'A' to conform to 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) { // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{20-26=()}}
return (c: 0, i: g(()))
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { _ in return A() } // expected-warning {{when calling this function in Swift 4 or later, you must pass a '()' tuple; did you mean for the input type to be '()'?}} {{10-16=()}}
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {} // expected-note {{where 'T' = 'Int'}}
// expected-note@-1 {{required by global function 'f8' where 'T' = '(Int, Double)'}}
f8(3, f4) // expected-error {{global function 'f8' requires that 'Int' conform to 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{type '(Int, Double)' cannot conform to 'P2'; only struct/enum/class types can conform to protocols}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{global function 'f5' requires that 'Int' conform to 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>( // expected-note {{in call to function 'myMap'}}
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{generic parameter 'T' could not be inferred}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
// SR-7599: This should be `cannot_call_non_function_value`
if s.count() == 0 {} // expected-error{{cannot call value of non-function type 'Int'}} {{13-15=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136()'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error@+1:49 {{cannot convert value of type 'Int' to expected argument type 'String'}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{cannot convert value of type 'Int' to expected condition type 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{cannot convert value of type 'Int' to expected condition type 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an argument of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' must be unwrapped to refer to member 'subscript' of wrapped base type '[Int]'}}
// expected-note@-1{{chain the optional using '?' to access member 'subscript' only for non-'nil' base values}}{{19-19=?}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}{{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {} // expected-note{{requirement specified as 'T' : 'AnyObject'}}
_ = r21553065Class<r21553065Protocol>() // expected-error {{'r21553065Class' requires that 'r21553065Protocol' be a class type}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{unable to infer closure type in the current context}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// Diagnose passing an array in lieu of variadic parameters
func variadic(_ x: Int...) {}
func variadicArrays(_ x: [Int]...) {}
func variadicAny(_ x: Any...) {}
struct HasVariadicSubscript {
subscript(_ x: Int...) -> Int {
get { 0 }
}
}
let foo = HasVariadicSubscript()
let array = [1,2,3]
let arrayWithOtherEltType = ["hello", "world"]
variadic(array) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
variadic([1,2,3]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}}
variadic([1,2,3,]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{10-11=}} {{16-17=}} {{17-18=}}
variadic(0, array, 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
variadic(0, [1,2,3], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}}
variadic(0, [1,2,3,], 4) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{13-14=}} {{19-20=}} {{20-21=}}
variadic(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}}
variadic(1, arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type 'Int'}}
// FIXME: SR-11104
variadic(["hello", "world"]) // expected-error 2 {{cannot convert value of type 'String' to expected element type 'Int'}}
// expected-error@-1 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-2 {{remove brackets to pass array elements directly}}
variadic([1] + [2] as [Int]) // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
foo[array] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
foo[[1,2,3]] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{5-6=}} {{11-12=}}
foo[0, [1,2,3], 4] // expected-error {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-1 {{remove brackets to pass array elements directly}} {{8-9=}} {{14-15=}}
variadicAny(array)
variadicAny([1,2,3])
variadicArrays(array)
variadicArrays([1,2,3])
variadicArrays(arrayWithOtherEltType) // expected-error {{cannot convert value of type '[String]' to expected argument type '[Int]'}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('String' and 'Int') are expected to be equal}}
variadicArrays(1,2,3) // expected-error 3 {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
protocol Proto {}
func f<T: Proto>(x: [T]) {}
func f(x: Int...) {}
f(x: [1,2,3])
// TODO(diagnostics): Diagnose both the missing conformance and the disallowed array splat to cover both overloads.
// expected-error@-2 {{cannot pass array of type '[Int]' as variadic arguments of type 'Int'}}
// expected-note@-3 {{remove brackets to pass array elements directly}}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call to function returning 'Int' is unused}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 3 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'CurriedClass'}}
// expected-error@-1:27 {{argument passed to call that takes no arguments}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{extra argument in call}}
// expected-error@-1 {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-1 {{extraneous argument label 'b:' in call}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// expected-error@-1 {{missing argument label 'b:' in call}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{incorrect argument labels in call (have 'c:', expected '_:b:')}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
// expected-error@-2 {{missing argument for parameter #1 in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing arguments for parameters #1, 'b' in call}} {{13-13=<#Int#>, b: <#Int#>}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self)
// expected-error@-1:13 {{cannot convert value of type 'CurriedClass' to expected argument type 'Int'}}
// expected-error@-2:17 {{missing argument for parameter 'b' in call}} {{17-17=, b: <#Int#>}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(a:)')}}
static func overload(b : Int) -> Color {} // expected-note {{incorrect labels for candidate (have: '(_:)', expected: '(b:)')}}
static func frob(_ a : Int, b : inout Int) -> Color {}
static var svar: Color { return .Red }
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{cannot convert value of type 'Array<(Int, _)>' to specified type '(Int, Color)'}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'Unknown'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown(description:)' expects argument of type 'String'}}
let _: Color = .Unknown(42) // expected-error {{missing argument label 'description:' in call}}
// expected-error@-1 {{cannot convert value of type 'Int' to expected argument type 'String'}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type '(Double, Float)' to specified type '(Int, Float)'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow()' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{no exact matches in call to static method 'overload'}}
let _: Color = .frob(1.0, &i) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1.0, b: &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{28-28=&}}
let _: Color = .frob(1, &d) // expected-error {{missing argument label 'b:' in call}}
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'?}}
someColor = .svar() // expected-error {{cannot call value of non-function type 'Color'}}
someColor = .svar(1) // expected-error {{cannot call value of non-function type 'Color'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{use of extraneous '&'}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
class GenClass<T> {}
struct GenStruct<T> {}
enum GenEnum<T> {}
func test(_ a : B) {
B.f1(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) // expected-error {{missing argument label 'a:' in call}}
// expected-error@-1 {{'nil' is not compatible with expected argument type 'AOpts'}}
a.f2(nil) // expected-error {{'nil' is not compatible with expected argument type 'AOpts'}}
func foo1(_ arg: Bool) -> Int {return nil}
func foo2<T>(_ arg: T) -> GenClass<T> {return nil}
func foo3<T>(_ arg: T) -> GenStruct<T> {return nil}
func foo4<T>(_ arg: T) -> GenEnum<T> {return nil}
// expected-error@-4 {{'nil' is incompatible with return type 'Int'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenClass<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenStruct<T>'}}
// expected-error@-4 {{'nil' is incompatible with return type 'GenEnum<T>'}}
let clsr1: () -> Int = {return nil}
let clsr2: () -> GenClass<Bool> = {return nil}
let clsr3: () -> GenStruct<String> = {return nil}
let clsr4: () -> GenEnum<Double?> = {return nil}
// expected-error@-4 {{'nil' is not compatible with closure result type 'Int'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenClass<Bool>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenStruct<String>'}}
// expected-error@-4 {{'nil' is not compatible with closure result type 'GenEnum<Double?>'}}
var number = 0
var genClassBool = GenClass<Bool>()
var funcFoo1 = foo1
number = nil
genClassBool = nil
funcFoo1 = nil
// expected-error@-3 {{'nil' cannot be assigned to type 'Int'}}
// expected-error@-3 {{'nil' cannot be assigned to type 'GenClass<Bool>'}}
// expected-error@-3 {{'nil' cannot be assigned to type '(Bool) -> Int'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions;}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to 'nil' always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' must be unwrapped to a value of type 'String'}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {} // expected-note {{'init(count:value:)' declared here}}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{trailing closure passed to parameter of type 'Int' that does not accept a closure}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error{{value of optional type '(Int, Int)?' must be unwrapped to refer to member '0' of wrapped base type '(Int, Int)'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' must be unwrapped to refer to member 'property' of wrapped base type 'ExampleStruct21890157'}}
// expected-note@-1{{chain the optional }}
// expected-note@-2{{force-unwrap using '!'}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note@-1 {{overloads for '-' exist with these partially matching parameter lists: (Double), (Float)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{value of type 'UnsafeMutableRawPointer' has no subscripts}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot convert value of type 'ClosedRange<Int>' to expected argument type 'Range<String.Index>'}}
_ = g[12] // expected-error {{'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{instance method 'append' expects a single parameter of type '(Int, Int)'}} {{16-16=(}} {{24-24=)}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
_ = a + b // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (UInt32, UInt32)}}
a += a +
b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}}
a += b // expected-error@:8 {{cannot convert value of type 'UInt32' to expected argument type 'Int'}}
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
postfix operator +++
postfix func +++ <T>(_: inout T) -> T { fatalError() }
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
_ = bytes[i+++] // expected-error {{cannot pass immutable value to mutating operator: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to 'nil' always returns true}}
// FIXME(integers): uncomment these tests once the < is no longer ambiguous
// _ = i < nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil < i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i <= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil <= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i > nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil > i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = i >= nil // _xpected-error {{type 'Int' is not optional, value can never be nil}}
// _ = nil >= i // _xpected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to 'nil' always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a:' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{missing argument label 'a:' in call}} {{36-36=a: }}
// expected-error@-1 {{cannot convert value of type 'Bool' to specified type 'Int'}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : BinaryInteger>() -> T? {
var buffer : T
let n = withUnsafeMutablePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<T>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtract(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{incorrect argument label in call (have 'contentsOfURL:usedEncoding:', expected 'contentsOf:usedEncoding:')}}
// expected-error@-2 {{'nil' is not compatible with expected argument type 'String'}}
// expected-error@-3 {{'nil' is not compatible with expected argument type 'String'}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found candidate with type '(Int) -> Int'}}
func value(y: String) -> String {} // expected-note {{found candidate with type '(String) -> String'}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{no exact matches in call to instance method 'value'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x:' in call}}
r27212391(3, y: 5) // expected-error {{incorrect argument labels in call (have '_:y:', expected 'x:_:')}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}} {{11-11=x: 5, }} {{12-18=}}
r27212391(y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'y:x:', expected 'x:_:')}} {{11-12=x}} {{17-20=}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{incorrect argument labels in call (have 'a:_:y:', expected 'a:x:_:')}}
r27212391(1, x: 3, y: 5) // expected-error {{incorrect argument labels in call (have '_:x:y:', expected 'a:x:_:')}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{incorrect argument labels in call (have 'a:y:x:', expected 'a:x:_:')}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}} {{17-17=x: 5, }} {{18-24=}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 4 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2)
// expected-error@-1 {{generic parameter 'A' could not be inferred}}
// expected-error@-2 {{generic parameter 'B' could not be inferred}}
// expected-note@-3 {{explicitly specify the generic arguments to fix this issue}} {{8-8=<Any, Any>}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
// <rdar://problem/29850459> Swift compiler misreports type error in ternary expression
let r29850459_flag = true
let r29850459_a: Int = 0
let r29850459_b: Int = 1
func r29850459() -> Bool { return false }
let _ = (r29850459_flag ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ({ true }() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = (r29850459() ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
let _ = ((r29850459_flag || r29850459()) ? r29850459_a : r29850459_b) + 42.0 // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists: (Double, Double), (Int, Int)}}
// SR-6272: Tailored diagnostics with fixits for numerical conversions
func SR_6272_a() {
enum Foo: Int {
case bar
}
// expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{35-35=Int(}} {{43-43=)}}
let _: Int = Foo.bar.rawValue * Float(0)
// expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{18-18=Float(}} {{34-34=)}}
let _: Float = Foo.bar.rawValue * Float(0)
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Int' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
Foo.bar.rawValue * Float(0)
}
func SR_6272_b() {
let lhs = Float(3)
let rhs = Int(0)
// expected-error@+1 {{cannot convert value of type 'Int' to expected argument type 'Float'}} {{24-24=Float(}} {{27-27=)}}
let _: Float = lhs * rhs
// expected-error@+1 {{cannot convert value of type 'Float' to expected argument type 'Int'}} {{16-16=Int(}} {{19-19=)}}
let _: Int = lhs * rhs
// expected-error@+2 {{binary operator '*' cannot be applied to operands of type 'Float' and 'Int'}} {{none}}
// expected-note@+1 {{overloads for '*' exist with these partially matching parameter lists: (Float, Float), (Int, Int)}}
lhs * rhs
}
func SR_6272_c() {
// expected-error@+1 {{cannot convert value of type 'String' to expected argument type 'Int'}} {{none}}
Int(3) * "0"
struct S {}
// expected-error@+1 {{cannot convert value of type 'S' to expected argument type 'Int'}} {{none}}
Int(10) * S()
}
struct SR_6272_D: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
static func +(lhs: SR_6272_D, rhs: Int) -> Float { return 42.0 } // expected-note 2 {{candidate expects value of type 'Int' for parameter #2}}
}
func SR_6272_d() {
let x: Float = 1.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x
// expected-error@+1 {{cannot convert value of type 'Double' to expected argument type 'Int'}} {{50-50=Int(}} {{54-54=)}}
let _: Float = SR_6272_D(integerLiteral: 42) + 42.0
// expected-error@+2 {{binary operator '+' cannot be applied to operands of type 'SR_6272_D' and 'Float'}} {{none}}
// expected-note@+1 {{overloads for '+' exist with these partially matching parameter lists: (Float, Float), (SR_6272_D, Int)}}
let _: Float = SR_6272_D(integerLiteral: 42) + x + 1.0
}
// Ambiguous overload inside a trailing closure
func ambiguousCall() -> Int {} // expected-note {{found this candidate}}
func ambiguousCall() -> Float {} // expected-note {{found this candidate}}
func takesClosure(fn: () -> ()) {}
takesClosure() { ambiguousCall() } // expected-error {{ambiguous use of 'ambiguousCall()'}}
// SR-4692: Useless diagnostics calling non-static method
class SR_4692_a {
private static func foo(x: Int, y: Bool) {
self.bar(x: x)
// expected-error@-1 {{instance member 'bar' cannot be used on type 'SR_4692_a'}}
}
private func bar(x: Int) {
}
}
class SR_4692_b {
static func a() {
self.f(x: 3, y: true)
// expected-error@-1 {{instance member 'f' cannot be used on type 'SR_4692_b'}}
}
private func f(a: Int, b: Bool, c: String) {
self.f(x: a, y: b)
}
private func f(x: Int, y: Bool) {
}
}
// rdar://problem/32101765 - Keypath diagnostics are not actionable/helpful
struct R32101765 { let prop32101765 = 0 }
let _: KeyPath<R32101765, Float> = \.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765
// expected-error@-1 {{key path value type 'Int' cannot be converted to contextual type 'Float'}}
let _: KeyPath<R32101765, Float> = \.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
let _: KeyPath<R32101765, Float> = \R32101765.prop32101765.unknown
// expected-error@-1 {{type 'Int' has no member 'unknown'}}
// rdar://problem/32390726 - Bad Diagnostic: Don't suggest `var` to `let` when binding inside for-statement
for var i in 0..<10 { // expected-warning {{variable 'i' was never mutated; consider removing 'var' to make it constant}} {{5-9=}}
_ = i + 1
}
// SR-5045 - Attempting to return result of reduce(_:_:) in a method with no return produces ambiguous error
func sr5045() {
let doubles: [Double] = [1, 2, 3]
return doubles.reduce(0, +)
// expected-error@-1 {{unexpected non-void return value in void function}}
}
// rdar://problem/32934129 - QoI: misleading diagnostic
class L_32934129<T : Comparable> {
init(_ value: T) { self.value = value }
init(_ value: T, _ next: L_32934129<T>?) {
self.value = value
self.next = next
}
var value: T
var next: L_32934129<T>? = nil
func length() -> Int {
func inner(_ list: L_32934129<T>?, _ count: Int) {
guard let list = list else { return count } // expected-error {{unexpected non-void return value in void function}}
return inner(list.next, count + 1)
}
return inner(self, 0) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}}
}
}
// rdar://problem/31671195 - QoI: erroneous diagnostic - cannot call value of non-function type
class C_31671195 {
var name: Int { fatalError() }
func name(_: Int) { fatalError() }
}
C_31671195().name(UInt(0))
// expected-error@-1 {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
// rdar://problem/28456467 - QoI: erroneous diagnostic - cannot call value of non-function type
class AST_28456467 {
var hasStateDef: Bool { return false }
}
protocol Expr_28456467 {}
class ListExpr_28456467 : AST_28456467, Expr_28456467 {
let elems: [Expr_28456467]
init(_ elems:[Expr_28456467] ) {
self.elems = elems
}
override var hasStateDef: Bool {
return elems.first(where: { $0.hasStateDef }) != nil
// expected-error@-1 {{value of type 'Expr_28456467' has no member 'hasStateDef'}}
}
}
// rdar://problem/31849281 - Let's play "bump the argument"
struct rdar31849281 { var foo, a, b, c: Int }
_ = rdar31849281(a: 101, b: 102, c: 103, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(a: 101, c: 103, b: 102, foo: 104) // expected-error {{argument 'foo' must precede argument 'a'}} {{18-18=foo: 104, }} {{40-50=}}
_ = rdar31849281(foo: 104, a: 101, c: 103, b: 102) // expected-error {{argument 'b' must precede argument 'c'}} {{36-36=b: 102, }} {{42-50=}}
_ = rdar31849281(b: 102, c: 103, a: 101, foo: 104) // expected-error {{incorrect argument labels in call (have 'b:c:a:foo:', expected 'foo:a:b:c:')}} {{18-19=foo}} {{26-27=a}} {{34-35=b}} {{42-45=c}}
_ = rdar31849281(foo: 104, b: 102, c: 103, a: 101) // expected-error {{argument 'a' must precede argument 'b'}} {{28-28=a: 101, }} {{42-50=}}
func var_31849281(_ a: Int, _ b: Int..., c: Int) {}
var_31849281(1, c: 10, 3, 4, 5, 6, 7, 8, 9) // expected-error {{unnamed argument #3 must precede argument 'c'}} {{17-17=3, 4, 5, 6, 7, 8, 9, }} {{22-43=}}
func fun_31849281(a: (Bool) -> Bool, b: (Int) -> (String), c: [Int?]) {}
fun_31849281(c: [nil, 42], a: { !$0 }, b: { (num: Int) -> String in return "\(num)" })
// expected-error @-1 {{incorrect argument labels in call (have 'c:a:b:', expected 'a:b:c:')}} {{14-15=a}} {{28-29=b}} {{40-41=c}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { (num: Int) -> String in return String(describing: num) })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { (num: Int) -> String in return String(describing: num) }, }} {{38-101=}}
fun_31849281(a: { !$0 }, c: [nil, 42], b: { "\($0)" })
// expected-error @-1 {{argument 'b' must precede argument 'c'}} {{26-26=b: { "\\($0)" }, }} {{38-54=}}
func f_31849281(x: Int, y: Int, z: Int) {}
f_31849281(42, y: 10, x: 20) // expected-error {{incorrect argument labels in call (have '_:y:x:', expected 'x:y:z:')}} {{12-12=x: }} {{23-24=z}}
func sr5081() {
var a = ["1", "2", "3", "4", "5"]
var b = [String]()
b = a[2...4] // expected-error {{cannot assign value of type 'ArraySlice<String>' to type '[String]'}}
}
// TODO(diagnostics):Figure out what to do when expressions are complex and completely broken
func rdar17170728() {
var i: Int? = 1
var j: Int?
var k: Int? = 2
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0! + $1! : ($0 ? $0! : ($1 ? $1! : nil))
// expected-error@-1 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}}
}
let _ = [i, j, k].reduce(0 as Int?) {
$0 && $1 ? $0 + $1 : ($0 ? $0 : ($1 ? $1 : nil))
// expected-error@-1 {{binary operator '+' cannot be applied to two 'Int?' operands}}
// expected-error@-2 4 {{optional type 'Int?' cannot be used as a boolean; test for '!= nil' instead}}
}
}
// https://bugs.swift.org/browse/SR-5934 - failure to emit diagnostic for bad
// generic constraints
func elephant<T, U>(_: T) where T : Collection, T.Element == U, T.Element : Hashable {} // expected-note {{where 'U' = 'T'}}
func platypus<T>(a: [T]) {
_ = elephant(a) // expected-error {{global function 'elephant' requires that 'T' conform to 'Hashable'}}
}
// Another case of the above.
func badTypes() {
let sequence:AnySequence<[Int]> = AnySequence() { AnyIterator() { [3] }}
let array = [Int](sequence)
// expected-error@-1 {{initializer 'init(_:)' requires the types 'Int' and '[Int]' be equivalent}}
}
// rdar://34357545
func unresolvedTypeExistential() -> Bool {
return (Int.self==_{})
// expected-error@-1 {{expression type 'Bool' is ambiguous without more context}}
}
func rdar43525641(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
rdar43525641(1, c: 2, 3) // Ok
do {
struct Array {}
let foo: Swift.Array = Array() // expected-error {{cannot convert value of type 'Array' to specified type 'Array<Element>'}}
// expected-error@-1 {{generic parameter 'Element' could not be inferred}}
struct Error {}
let bar: Swift.Error = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz: (Swift.Error) = Error() //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz2: Swift.Error = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz3: (Swift.Error) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
let baz4: ((Swift.Error)) = (Error()) //expected-error {{value of type 'diagnostics.Error' does not conform to specified type 'Swift.Error'}}
}
// SyntaxSugarTypes with unresolved types
func takesGenericArray<T>(_ x: [T]) {}
takesGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int]'}}
func takesNestedGenericArray<T>(_ x: [[T]]) {}
takesNestedGenericArray(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[[Int]]'}}
func takesSetOfGenericArrays<T>(_ x: Set<[T]>) {}
takesSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<[Int]>'}}
func takesArrayOfSetOfGenericArrays<T>(_ x: [Set<[T]>]) {}
takesArrayOfSetOfGenericArrays(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Set<[Int]>]'}}
func takesArrayOfGenericOptionals<T>(_ x: [T?]) {}
takesArrayOfGenericOptionals(1) // expected-error {{cannot convert value of type 'Int' to expected argument type '[Int?]'}}
func takesGenericDictionary<T, U>(_ x: [T : U]) {} // expected-note {{in call to function 'takesGenericDictionary'}}
takesGenericDictionary(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : U]'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
// expected-error@-2 {{generic parameter 'U' could not be inferred}}
typealias Z = Int
func takesGenericDictionaryWithTypealias<T>(_ x: [T : Z]) {} // expected-note {{in call to function 'takesGenericDictionaryWithTypealias'}}
takesGenericDictionaryWithTypealias(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '[T : Z]'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
func takesGenericFunction<T>(_ x: ([T]) -> Void) {} // expected-note {{in call to function 'takesGenericFunction'}}
takesGenericFunction(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T]) -> Void'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
func takesTuple<T>(_ x: ([T], [T])) {} // expected-note {{in call to function 'takesTuple'}}
takesTuple(true) // expected-error {{cannot convert value of type 'Bool' to expected argument type '([T], [T])'}}
// expected-error@-1 {{generic parameter 'T' could not be inferred}}
| apache-2.0 | 1c01cb24f5d523546ed6a962081ce1cf | 47.419453 | 228 | 0.668236 | 3.561567 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.